使用短代码更改页面标题

时间:2013-03-09 15:26:37

标签: wordpress wordpress-plugin

我正在编写插件,我使用短代码来呈现页面内容。我想更改页面标题。我用过这个:

// Change the title of the page of the charts to add the current month. 
add_filter('the_title', 'charts_title', 10, 2);
function charts_title($title, $id) { 
  $title .= ' ' . date('F Y');
  return $title;
}

但它确实适用于所有帖子和页面。我只能为包含我创建的短代码的页面执行此操作吗?我试图这样做,但它不起作用。

add_shortcode('charts-vote', 'charts_vote');
function charts_vote($atts) {
    // Add the filter only in the short code function callback.
    add_filter('the_title', 'charts_title', 10, 2);   

    // ... // 
    return $content;
}

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

我了解您的设置细节可能需要检查Shortcode,但也许可以使用自定义字段:

add_filter( 'the_title', 'charts_title_so_15312385', 10, 2 );

function charts_title_so_15312385( $title, $post_id ) 
{ 
    // Admin area, bail out
    if( is_admin() )
        return $title;

    // Custom field not set, bail out
    $mod_title = get_post_meta( $post_id, 'mod_title', true );
    if( !$mod_title )
        return $title;

    // Ok, modify title
    $title .= ' ' . date( 'F Y' );
    return $title;
}

短代码甚至可以与自定义字段“对话”以进行扩展配置。

为了便于使用,您可以制作Custom Meta Box或使用Advanced Custom Fields之类的插件。