wp -标题过滤器不分配变量


WP-Title filter not assigning variable

我想将术语名称设置为变量

if(isset($wp_taxonomies)) {
    $term = get_term_by(
        'slug', 
         get_query_var('term'), 
         get_query_var('taxonomy')
    );
    if($term) {
        // do stuff
    }
} 
function assignPageTitle(){     
    return $term>name;
}
add_filter('wp_title', 'assignPageTitle');
get_header();

此代码位于taxonomy.php文件中,$term>name;返回名称,但只有当我回显时,标题上才会给我这些错误:

注意:在/home/jshomesc/public_html/wp-content/themes/jshomes/taxonomy.php12

使用未定义的常量name -假设'name'

注意:未定义变量:term in /home/jshomesc/public_html/wp-content/themes/jshomes/taxonomy.php on line 12

有几个问题:

  1. 要访问术语的name属性,语法如下$term->name .

  2. assignPageTitle函数不知道您刚刚在它上面检索的全局$term变量。它试图检索尚未定义的本地$term变量的name属性。

要修复它,添加global关键字(并检查它是否已填充):

function assignPageTitle(){  
    // Now the function will know about the $term you've retrieved above  
    global $term;
    // Do we have a $term and name?
    if(isset($term, $term->name)){
        return $term->name;
    }
    return "No term for you...";
}