是否可以将其转换为数组:
function manipulate_post_title($title){
global $post;
if ($post->ID == 1) {$title = $title.\'suffix\';}
if ($post->ID == 2) {$title = $title.\'different_suffix\';}
}
add_filter (\'the_title\',\'manipulate_post_title\',10,1);
类似于:
\'1\' => $title.\'suffix\',
\'2\' => $title.\'different_suffix\'
基于您的代码的新版本(不起作用):
function manipulate_post_title($title){
global $post;
$title = get_the_title();
$title_array = array(
\'1\' => $title.\'suffix\',
\'2\' => \'prefix\'.$title,
\'3\' => \'completely different title\'
);
if ( is_single() && isset($title_array[$post->ID]) ) {
$title = $title_array[$post->ID];
}
return $title; // Don\'t forget the return value!
}
add_filter (\'the_title\',\'manipulate_post_title\',10,1);
最合适的回答,由SO网友:Philipp 整理而成
您的示例代码可以很容易地转换为数组,如下所示:
更新并改进了新示例的代码:
function manipulate_post_title( $title, $post_id ) {
$title_array = array(
\'1153\' => $title . \'-suffix\',
\'2\' => \'prefix-\' . $title,
\'3\' => \'completely different title\',
);
if ( is_single() && isset( $title_array[ $post_id ] ) ) {
$title = $title_array[ $post_id ];
} else {
// For debugging I set the title to "[123] Title" so I can find the post_id
$title = \'[\' . $post_id . \'] \' . $title;
}
return $title;
}
add_filter( \'the_title\', \'manipulate_post_title\', 99, 2 );
您的代码无法工作,因为它有一个无限循环:您调用过滤器中的函数“the\\u title()”“the\\u title”(这将反复调用过滤器,直到发生内存错误为止)
上面的代码适用于我的安装,当WordPress函数“get\\u The\\u title()”或“The\\u title()”返回标题时,会更改标题。在Twenty14主题中,它会更改显示在<h1>
页面的标记,但不是<title>
显示在浏览器选项卡中的元素!
Example screenshot from my test-page