Wordpress - 如果复选框输出与页面标题匹配,则显示文本

时间:2011-05-19 08:36:54

标签: php wordpress custom-fields

我想显示已将其复选框勾选为Branding的项目,如果它位于Branding页面上(即页面标题为Branding)。

稍微解释一下代码:

此行显示已为每个项目勾选的所有复选框,因此如果已勾选,则会输出“品牌”,“网页”,“打印”。

implode(', ',get_field('categories')

下一行只是检查页面标题是“品牌”:

implode(', ',get_field('categories')

我正在尝试将这两者都放在if语句中,它只输出复选框,如果它们与标题匹配,则输出它们。

<?php if(implode(', ',get_field('categories')) && $grid_title == "Branding"); {
echo "testing"; 
}
?>

上面的代码显示了我想要做的事情,但它并没有完全奏效。

重要提示:我正在使用this plugin创建自定义复选框,因此请牢记这一点。

=============================

更新 非常感谢Adam Kiss解决我的问题,小问题更新:

我怎么能整齐地编码 - 使用你的答案,Branding只是复选框的一个例子,还有其他一些如Web,Print,Social,那么我怎样才能将它们与页面标题相匹配呢?

因此,如果选中字段等于页面标题“品牌”,则执行 OR 选中字段等于页面标题“web” OR 选中字段等于页面标题“打印”。

1 个答案:

答案 0 :(得分:0)

您正在寻找的功能是in_array

<?php
   if(
       in_array("Branding", get_field('categories')) 
       && $grid_title == "Branding"
   ){
     echo "testing";
   }

注意:这假设该内爆的结果是带有“Branding”,“Web”等字符串的数组。

修改:由于我们正在使用implode(),我假设get_field返回类型array,因此我们将内爆(我感到困惑了一段时间)

编辑:抱歉,离开了:]

您可以使用array_intersect

用法:

$categories = get_field('categories');
$cats_iwant = array("Branding", "Print", "Design");

$inarray = array_intersect($categories, $cats_iwant);
//this '$inarray' now has values like 'Branding', 'Design' which are in both arrays

if (count($inarray) > 0) {
  //we have at least one common word ('Branding', ...)
}

//short version
if (count(array_intersect(get_field('categories'),array(
    'Branding', 'Design', 'Print'
   ))) > 0)
{
 //do stuff
}