How to modify page title in shortcode?

前端 未结 2 514
半阙折子戏
半阙折子戏 2021-01-22 00: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 exec

相关标签:
2条回答
  • 2021-01-22 01:38

    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');
    
    0 讨论(0)
  • 2021-01-22 01:42

    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.

    0 讨论(0)
提交回复
热议问题