如何用简码修改页面标题?

4th*_*ace 2 php wordpress shortcode

如何用短代码修改特定页面的页面标题?

以下将更改标题,但它会针对每个页面执行。我需要更多地控制它的执行位置。

function assignPageTitle(){
  return "Title goes here";
}
add_filter('wp_title', 'assignPageTitle');
Run Code Online (Sandbox Code Playgroud)

有没有办法在短代码函数中调用上述内容?我知道如何使用 do_shortcode() 但上面是一个过滤器。

我的目标是根据 URL 参数修改页面标题。这只发生在特定页面上。

小智 5

尽管 WordPress 短代码的设计初衷不是为了实现此目的,但它是可以做到的。问题是在发送头部之后处理短代码,因此解决方案是在发送头部之前处理短代码。

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';
} );
Run Code Online (Sandbox Code Playgroud)

关键点是当过滤器“pre_get_document_title”完成时,全局 $post 对象被设置并且 $post->post_content 可用。所以,你现在可以找到这篇文章的简码。

当短代码通常被调用时,它会用空字符串替换自身,因此它对 post_content 没有影响。但是,当从过滤器“pre_get_document_title”调用时,它可以根据其参数 $atts 和全局 $post 计算标题。