自动将自定义字段添加到帖子标题

时间:2018-03-07 作者:juicebyah

我要在帖子标题中添加自定义字段,

我的帖子标题是"Marroon Five" 我的自定义字段是"release-year" 并且有价值"2017" .

因此,如何进行输出:Marroon Five (2017)

这是我搜索后发现的

add_action(\'save_post\', \'update_term_title\');
function update_term_title($post_id)
{
    if(defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) 
        return;
    if(!current_user_can(\'edit_post\', $post_id))
        return;

    //Replace \'release-year\' with whatever your custom taxonomy slug is
    $terms = wp_get_post_terms($post_id, \'release-year\');

    if(empty($terms))
        return;

    $title = false;
    foreach($terms as $term)
    {
        if($term->parent)
        {
            $parent = get_term($term->parent, \'release-year\');
            $title = $term->name.\' \'.$parent->name;
            break;
        }
    }
    /*Default to first selected term name if no children were found*/
    $title = $title ? $title : $terms[0]->name;

    /*We must disable this hook and reenable from within
    if we don\'t want to get caught in a loop*/
    remove_action(\'save_post\', \'update_term_title\');
    $update = array(
        \'ID\'=>$post_id,
        \'post_name\'=>sanitize_title_with_dashes($title),
        \'post_title\'=>$title
    );
    wp_update_post($update);
    add_action(\'save_post\', \'update_term_title\');
}
唯一的问题是,此代码将所有帖子标题替换为自定义字段值"2017"

希望有人能修复这是我想要的返回输出

非常感谢。

1 个回复
SO网友:Jason Lawton

您可以编写一个函数来钩住标题的显示,然后在显示标题时,它将获取自定义字段的值并将其附加到标题。这样,您就不会每次保存帖子时都编辑/更改标题。

您可以这样做:

function append_year( $title ) {
    global $post;
    $terms = wp_get_post_terms( $post->ID, \'release-year\', array("fields" => "names") );

    if ( count( $terms ) ) {
        return $title . \'(\' . $terms[0] . \')\';
    } else {
        return $title;
    }
}

add_filter( \'the_title\', array($this, \'append_title\' ) );
wp_get_post_terms 返回一个数组,您可以向其传递一个参数数组来配置所需的内容see the wp_get_post_terms documentation.

上述代码改编自this other SO post about appending title text

结束

相关推荐

变量中带有撇号的GET_PAGE_BY_TITLE

我在创建查询某些帖子的快捷码时遇到了一些问题。这是我的代码的基础:function shortcode_equipment($atts, $content = null) { $equipment = get_page_by_title($content, OBJECT, \'equipment\'); $loop = new WP_Query( array( \'posts_per_page\' => 1, \'po