Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save wp-seopress/52b10cdcd1308b233184ea190e665cdf to your computer and use it in GitHub Desktop.

Select an option

Save wp-seopress/52b10cdcd1308b233184ea190e665cdf to your computer and use it in GitHub Desktop.
Strip the language prefix from Search Console URLs before matching
<?php
/**
* SEOPress PRO — Strip the language prefix from Search Console URLs before matching.
*
* Multilingual plugins (Polylang, WPML, TranslatePress…) prepend a language segment
* (e.g. /en/, /fr/) to public URLs but do not register that segment in WP_Rewrite.
* As a result, url_to_postid() cannot match the raw URL returned by Google Search
* Console. This snippet removes a known list of language prefixes so SEOPress can
* resolve the WordPress post and store GSC impressions / clicks / CTR / position
* against it.
*
* Hook: seopress_search_console_match_url
* Plugin: SEOPress PRO 9.9+
*/
add_filter( 'seopress_search_console_match_url', 'sp_search_console_match_url', 10, 2 );
function sp_search_console_match_url( $clean_url, $url ) {
// Adjust to the languages enabled on your site.
$language_prefixes = array( 'en', 'fr', 'es', 'de', 'it' );
$parts = wp_parse_url( $clean_url );
if ( empty( $parts['path'] ) ) {
return $clean_url;
}
// Detect /xx/ at the very start of the path.
if ( preg_match( '#^/(' . implode( '|', $language_prefixes ) . ')(/|$)#', $parts['path'], $matches ) ) {
$parts['path'] = substr( $parts['path'], strlen( $matches[1] ) + 1 );
if ( '' === $parts['path'] ) {
$parts['path'] = '/';
}
$clean_url = $parts['scheme'] . '://' . $parts['host'] . $parts['path'];
}
return $clean_url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment