The full title of the post with all filters in the plugins returns wp_document_title() .
The problem is that this function only works with the current page. The following code "tricks" this function by saving the current wp_query query, making a new main (this is important!) WordPress query using query_posts() , resetting the query result using wp_reset_query() and restoring the old query in the global wp_query variable.
function get_wp_title( $id ) { global $wp_query; $old_wp_query = null; $old_wp_query = $wp_query; $args = array( 'post_type' => 'any', 'post_status' => 'publish', 'p' => $id, ); query_posts( $args ); if ( class_exists( WPSEO_Frontend ) ) { WPSEO_Frontend::get_instance()->reset(); } $title = wp_get_document_title(); wp_reset_query(); if ( ! empty( $old_wp_query ) ) { $GLOBALS['wp_query'] = $old_wp_query; unset( $old_wp_query ); } return $title; }
Using:
echo get_wp_title( $post_id );
Code tested, works.
UPDATE
When using the Yoast SEO plugin, the situation becomes much more complicated. This plugin itself accesses the internal global variables of WordPress and caches the page title in the private member of its class. In order to bypass the caching of Yoast SEO, the following lines were added to the code:
if ( class_exists( WPSEO_Frontend ) ) { WPSEO_Frontend::get_instance()->reset(); }
It is impossible to make any common code for any SEO plugin , as stated in the question. Only for Yoast had to resort to in-depth analysis of its code with a debugger to add just one function call.
UPDATE
Since there were questions about the health of the code, I provide step-by-step instructions for creating a test case.
- A test page so733846 has been created on the site test.kagg.eu
- The page-so733846.php file has been created in the theme folder.
The following code is placed in the file.
<?php // 733846 function get_wp_title( $id ) { global $wp_query; $old_wp_query = null; $old_wp_query = $wp_query; $args = array( 'post_type' => 'any', 'post_status' => 'publish', 'p' => $id, ); query_posts( $args ); if ( class_exists( WPSEO_Frontend ) ) { WPSEO_Frontend::get_instance()->reset(); } $title = wp_get_document_title(); wp_reset_query(); if ( ! empty( $old_wp_query ) ) { $GLOBALS['wp_query'] = $old_wp_query; unset( $old_wp_query ); } return $title; } function so_733846() { $wp_query = new WP_Query( [ 'post_type' => 'any', 'post_status' => 'publish', 'posts_per_page' => - 1, ] ); if ( $wp_query->have_posts() ) { while ( $wp_query->have_posts() ) { $wp_query->the_post(); $id = get_the_id(); echo get_wp_title( $id ) . '<br>'; } } wp_reset_postdata(); } so_733846();
The result of the work can be seen here: http://test.kagg.eu/so733846/
He is such a:
