How to modify page title in shortcode?

前端 未结 2 637
半阙折子戏
半阙折子戏 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: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.

提交回复
热议问题