How to modify page title in shortcode?

孤人 提交于 2019-12-02 06:29:37

问题


How do I modify a page title for specific pages in shortcode?

The following will change the title but it executes for every page. I need more control over where it executes.

function assignPageTitle(){
  return "Title goes here";
}
add_filter('wp_title', 'assignPageTitle');

Is there a way to call the above in a shortcode function? I know how to use do_shortcode() but the above is a filter.

My goal is to modify the page title based on a URL parameter. This only happens for specific pages.


回答1:


Taken from the WordPress Codex

Introduced in WordPress 2.5 is the Shortcode API, a simple set of functions for creating macro codes for use in post content.

This would suggest that you can't control page titles using shortcodes as the shortcode is run inside the post content at which point the title tag has already been rendered and is then too late.

What is it exactly that you want to do? Using the Yoast SEO Plugin you can set Post and Page titles within each post if this is what you want to do?

You could create your custom plugin based on your URL parameters as so:

function assignPageTitle(){

if( $_GET['query'] == 'something' ) { return 'something'; }

elseif( $_GET['query'] == 'something-else' ) { return 'something-else'; }

else { return "Default Title"; }

}

add_filter('wp_title', 'assignPageTitle');



回答2:


Although WordPress shortcodes was not designed to do this, it can be done. The problem is shortcodes are processed AFTER the head section is sent so the solution is to process the shortcode BEFORE the head section is sent.

add_filter( 'pre_get_document_title', function( $title ) {
    global $post;
    if ( ! $post || ! $post->post_content ) {
        return $title;
    }
    if ( preg_match( '#\[mc_set_title.*\]#', $post->post_content, $matches ) !== 1 ) {
        return '';
    }
    return do_shortcode( $matches[0] );
} );

add_shortcode( 'mc_set_title', function( $atts ) {
    if ( ! doing_filter( 'pre_get_document_title' ) ) {
        # just remove the shortcode from post content in normal shortcode processing
        return '';
    }
    # in filter 'pre_get_document_title' - you can use $atts and global $post to compute the title
    return 'MC TITLE';
} );

The critical point is when the filter 'pre_get_document_title' is done the global $post object is set and $post->post_content is available. So, you can find the shortcodes for this post at this time.

When the shortcode is normally called it replaces itself with the empty string so it has no effect on the post_content. However, when called from the filter 'pre_get_document_title' it can compute the title from its arguments $atts and the global $post.



来源:https://stackoverflow.com/questions/15665247/how-to-modify-page-title-in-shortcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!