WordPress功能in_category无法按预期工作


Wordpress function in_category not working as expected

这让我发疯,我尝试了各种不同的事情。 从本质上讲,所需的效果是使用内置的in_category功能在Wordpress中定位两个不同的类别。

这是我目前的代码:

if(in_category( array("Snacks", "Other Nuts") )) :
 //do something
endif;

这将适用于类别Snacks,但不适用于类别Other Nuts。 当我用另一个类别名称(如Confections)替换Other Nuts时,它可以完美运行。

我假设这与类别名称中的空格有关 Other Nuts . 虽然,我已经尝试使用它的类别ID和类别蛞蝓无济于事。

知道这里发生了什么吗??

通了。

假设您有两个类别,一个是另一个类别的父类别,如下所示:

Other Nuts (Parent)
    Almonds (Child)

如果您在 Wordpress 中发布帖子并将其分类为Almonds并运行一个简单的循环,例如

if(have_posts()) :
  while(have_posts()) : the_post();
  // run your loop
  endwhile;
endif;

您将获得属于分类在 Almonds 中的Other Nuts父类别的 Almonds 帖子的输出。 现在,如果您要改为运行此循环:

if(have_posts()) :
  while(have_posts()) : the_post();
    if(in_category('Other Nuts')) :  
       // run your loop
    endif;
  endwhile;
endif;

你什么也得不到。 原因是因为您只在Almonds中对帖子进行了分类,而不是在Other Nuts中。 在这种情况下,WordPress不会在父类别和子类别之间建立联系。 在子项中分类不会在父项中对其进行分类。

从本质上讲,这应该根据您期望的所有 ID 检查帖子的所有当前类别 ID,然后根据您所期望的内容检查所有父类别 ID。您可以比较类别名称,但与此代码略有不同。

第 1 步:将其放入您的函数.php文件中:

function check_category_family( $categories, $expected_ids ){
  foreach( $categories as $i ){
    if( in_array( intval( $i->category_parent ), $expected_ids ) ){
      return true;
    }
  }
}

第 2 步:将此伪代码放入您正在构建的任何类别模板中:

$categories = get_the_category();
$expected_ids = array( /*PUT YOUR CATEGORY IDS AS INTEGERS IN HERE*/ );
if( in_category( $expected_ids ) || check_category_family( $categories, $expected_ids ) ){
  //run the loop
} else {
  //redirect?
}