Last active
June 13, 2019 09:58
-
-
Save rvdsteege/1a08a970427d866e895a8d010af1ef5a to your computer and use it in GitHub Desktop.
Set Yoast SEO canonical URL meta for given post types and taxonomies to current link and perform given URL replacements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Set Yoast SEO canonical URL meta for given post types and taxonomies | |
* to current link and perform given URL replacements. | |
* | |
* To run, set query variable: `/wp-admin/?pronamic_set_canonical=true`. | |
* | |
* @return void | |
*/ | |
add_action( 'init', 'pronamic_wpseo_set_canonical' ); | |
function pronamic_wpseo_set_canonical() { | |
// Post types to process. | |
$post_types = array( | |
'download', | |
'location', | |
'market', | |
'page', | |
'product', | |
); | |
// Taxonomies to process. | |
$taxonomies = array( | |
'application', | |
'category', | |
'download_category', | |
'location_category', | |
'market_category', | |
'product_category', | |
); | |
// URL replacements. | |
$replacements = array( | |
'/de-de/' => '/de/', | |
'/fr-fr/' => '/fr/', | |
); | |
/* --- DO NOT EDIT BELOW THIS LINE --- */ | |
if ( ! filter_has_var( INPUT_GET, 'pronamic_set_canonical' ) ) { | |
return; | |
} | |
// Post types. | |
$query = new WP_Query( | |
array( | |
'post_type' => $post_types, | |
'post_status' => 'any', | |
'fields' => 'ids', | |
'nopaging' => true, | |
) | |
); | |
// Update Yoast SEO canonical URL post meta. | |
foreach ( $query->posts as $post_id ) { | |
$permalink = get_permalink( $post_id ); | |
$canonical = strtr( $permalink, $replacements ); | |
update_post_meta( $post_id, '_yoast_wpseo_canonical', $canonical ); | |
} | |
// Taxonomies. | |
$query = new WP_Term_Query( | |
array( | |
'taxonomy' => $taxonomies, | |
'fields' => 'ids', | |
) | |
); | |
// Update Yoast SEO canonical URL term meta. | |
foreach ( $query->terms as $term_id ) { | |
$term_link = get_term_link( $term_id ); | |
$canonical = strtr( $term_link, $replacements ); | |
update_term_meta( $term_id, '_yoast_wpseo_canonical', $canonical ); | |
} | |
} | |
/** | |
* Yoast SEO canonical URL filter for post archives. | |
* | |
* @return string | |
*/ | |
add_filter( 'wpseo_canonical', 'pronamic_wpseo_canonical_archive_url' ); | |
function pronamic_wpseo_canonical_archive_url( $canonical ) { | |
if ( ! is_post_type_archive() ) { | |
return $canonical; | |
} | |
// Replacements. | |
$replacements = array( | |
'/de-de/' => '/de/', | |
'/fr-fr/' => '/fr/', | |
); | |
$canonical = strtr( $canonical, $replacements ); | |
return $canonical; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment