Last active
May 22, 2026 13:34
-
-
Save wp-seopress/857cae6a184a790bc80a875a5217046e to your computer and use it in GitHub Desktop.
Last-resort post ID resolver for Search Console rows via Polylang
This file contains hidden or 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 | |
| /** | |
| * SEOPress PRO — Last-resort post ID resolver for Search Console rows via Polylang. | |
| * | |
| * When url_to_postid() returns 0 (typically because the URL belongs to a translation | |
| * whose permalink is owned by the multilingual plugin), this snippet asks Polylang | |
| * to resolve the URL using its own router. The resolved post then receives the | |
| * GSC metrics (clicks, impressions, CTR, position) on each daily sync. | |
| * | |
| * Hook: seopress_search_console_match_post_id | |
| * Plugin: SEOPress PRO 9.9+ | |
| * Requires: Polylang (or Polylang Pro) | |
| */ | |
| add_filter( 'seopress_search_console_match_post_id', 'sp_search_console_match_post_id', 10, 3 ); | |
| function sp_search_console_match_post_id( $post_id, $clean_url, $url ) { | |
| // Already resolved by SEOPress / WP core, nothing to do. | |
| if ( $post_id > 0 ) { | |
| return $post_id; | |
| } | |
| if ( ! function_exists( 'PLL' ) ) { | |
| return $post_id; | |
| } | |
| $pll = PLL(); | |
| if ( empty( $pll->links_model ) || ! method_exists( $pll->links_model, 'get_language_from_url' ) ) { | |
| return $post_id; | |
| } | |
| // Ask Polylang which language owns this URL, then strip the language slug. | |
| $language = $pll->links_model->get_language_from_url( $clean_url ); | |
| $untranslated = $pll->links_model->remove_language_from_link( $clean_url ); | |
| $resolved_id = url_to_postid( $untranslated ); | |
| if ( $resolved_id > 0 && $language && function_exists( 'pll_get_post' ) ) { | |
| // Get the translated post in the language returned by GSC. | |
| $translated_id = pll_get_post( $resolved_id, $language ); | |
| if ( $translated_id ) { | |
| return (int) $translated_id; | |
| } | |
| } | |
| return $resolved_id > 0 ? (int) $resolved_id : (int) $post_id; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment