首页 > 解决方案 > 尝试通过 function.php 将一些自定义文本添加到 Wordpress 帖子标题中

问题描述

我需要在 wordpress 帖子标题中动态添加自定义文本,我试图通过 function.php 中的此代码添加

以下代码不起作用

add_filter('the_title', 'new_title', 10, 2);
function new_title($title, $id) {
    if('babysitters' == get_post_type($id)){
        $exclusive = get_field('exclusive');
        $newtitle = $title .', ' .$exclusive->y;

    }
    else{

        $newtitle = $title;
    }
    return $newtitle;
}

标签: javascriptphpwordpressadvanced-custom-fields

解决方案


您正在使用get_field但它不在 Wordpress“循环”中,因此您需要将帖子 ID 传递给函数,以便它知道要使用的帖子。

假设 get_field 将一个对象返回到$exclusive变量中,您只需将函数更改为以下内容:

add_filter('the_title', 'new_title', 10, 2);
function new_title($title, $id) {
    if('babysitters' == get_post_type($id)){
        $exclusive = get_field('exclusive', $id);   // pass the id into get_field
        $title = $title .', ' .$exclusive->y;
    }
    return $title;
}

推荐阅读