我试图过滤帖子的标题,以便只在首页上使用结果,但它也会影响仪表板,因此任何可用的条件都只影响前端。
这是我的代码,它显示了标题与主要类别名称的组合,它可以工作,但仅限于我提到的事项:
function edit_title($title, $id){
if(get_post_type($id) == \'post\'){
$allcats = get_categories();
$catnames = array();
foreach ($allcats as $catob){
$catnames[$catob->name] = $catob->cat_ID;
}
foreach ($catnames as $catname => $catid){
$args = array (\'fields\' => \'names\');
$catlist = wp_get_post_categories($id, $args);
if (in_array($catname,$catlist)){
$cat = get_category( $catid );
$catancestorsids = get_ancestors ($catid , \'category\');
$greatgrandparent = array();
foreach ($catancestorsids as $catancestorid){
$catancestorob = get_category( $catancestorid );
if($catancestorob->category_parent == 0){
$greatgrandparent[] = $catancestorob->name;
}
}
$title = \'<span style="background-color:#333333; padding:3px; color:#ffffff; border-radius: 4px;">\'.$greatgrandparent[0].\':</span> \'.$title;
}
}
}
return $title;
}
add_filter(\'the_title\', \'edit_title\',10,2);