Wordpress检查single_cat_title()是否包含关键字


Wordpress check if single_cat_title() contains keyword

如果类别标题包含关键字,我想有条件地将关键字添加到标题的末尾。

我正在使用以下代码,它正在打印Amish Cookies,但我想要Amish Cookies Recipes

如何有条件地添加"Recipes"到标题的最后?

else if( is_archive() ){
    //echo __('Archive for ', 'recipe') . single_month_title(' ', false);
    echo single_cat_title('Amish ') . single_month_title(' ', false) . (' Recipes'); 
}

你的问题有点不清楚,但我认为这是你想要的:

<?php
        if( is_archive() ){
            $current_category = single_cat_title("", false); // Get name of current category
            // If current category contains the string "Recipes" don't add it at the end of the name    
            if (strpos($current_category,'Recipes') !== false) {
                echo single_cat_title('Amish '). single_month_title(' ',false); 
            } else {
                echo single_cat_title('Amish ') . single_month_title(' ',false) . (' Recipes'); 
            }
        }
?>

由于您使用Amish 硬编码前缀,并且不会中断对单词Recipes的搜索,因此您可以通过仅调用辅助函数single_cat_title()一次来编写D.R.Y.代码。

然后你可以搜索Recipesstrpos()str_contains()取决于你的PHP版本。

$catTitle = single_cat_title('Amish ', false);
echo $catTitle
     . single_month_title(' ', false)
     . (str_contains($catTitle, 'Recipes') ? ' Recipes' : '');

注意,如果第二个参数没有被设置为false,辅助函数将打印它们的有效负载,而不是返回它。将echo与已经打印其数据的函数组合在一起是没有意义的。