【问题标题】:get_template_part if page has a custom taxonomyget_template_part 如果页面有自定义分类
【发布时间】:2020-01-09 14:59:48
【问题描述】:

我试图根据页面或帖子被标记的类别显示不同的标题菜单。我创建了两个工具集分类法、类别和酒店。

我希望所有酒店都有自己的菜单、徽标和预订菜单,但我无法让 php 工作并定位类别。

我尝试了几个sn-ps,例如这个:

*< ?php if( has_term('skaga', 'hoteller') {

get_template_part('includes/partials/header/header-menu-skaga'); }?>*

我还尝试了另一个在不同网站上工作的方法,但它针对两种分类法,我只需要它针对一种分类法。

*< ?php if( has_term('puder', 'produkttype') || has_term('senge', 'produkttype')) {

get_template_part('partials/sections/section', 'trustpilot'); } ?>*

我希望有人能指出我做错了什么。非常感谢所有帮助!

谢谢

【问题讨论】:

    标签: php wordpress get advanced-custom-fields


    【解决方案1】:

    我不确定为什么 WP 核心 has_term() 函数在这种情况下不起作用,但您可以执行以下操作,使用 get_the_terms() 并在结果上执行 array_search()

    function has_custom_taxonomy_term($termSlug, $taxonomy, $postId = null) {
        $terms = get_the_terms($postId, $taxonomy);
        if (isset($terms->errors)) {
            // taxonomy doesn't exist
            return false;
        }
    
        return array_search($termSlug, array_column($terms, 'slug')) !== false;
    }
    
    
    if (has_custom_taxonomy_term('skaga', 'hoteller')) {
        get_template_part( 'includes/partials/header/header-menu-skaga' );
    }
    

    【讨论】:

      【解决方案2】:

      @Benj

      嗨,本,

      感谢您的回复。

      我已经尝试过,并尝试对其余的分类进行 and and elseif,所以他们得到了另一个模板部分,但没有运气。

      这就是我尝试使用它的方式,你能发现错误的部分吗?

      function has_custom_taxonomy_term($termSlug, $taxonomy, $postId = null) {
      $terms = get_the_terms($postId, $taxonomy);
      if (isset($terms->errors)) {
          // taxonomy doesn't exist
          return false;
      }
      
      return array_search($termSlug, array_column($terms, 'slug')) !== false;
       }
      if (has_custom_taxonomy_term('sabrokro', 'hoteller')) {
      get_template_part( 'includes/partials/header/header-menu-sabrokro' ); 
      }
      elseif (has_custom_taxonomy_term('odder-parkhotel', 'hoteller')) {
      get_template_part( 'includes/partials/header/header-menu-odder' ); 
      }
      elseif (has_custom_taxonomy_term('skaga', 'hoteller')) {
      get_template_part( 'includes/partials/header/header-menu-skaga' ); 
      }
      elseif (has_custom_taxonomy_term('hotel-hanstholm', 'hoteller')) {
      get_template_part( 'includes/partials/header/header-menu-hanstholm' );
      }
      

      再次感谢!

      【讨论】:

      • 您的代码在have_posts() 循环内吗?您可能需要添加 $postId 值,否则
      • 不,完全如上图所示。我不是 php wiz,所以我不知道用 $postId 准确地编写它。
      • 我似乎无法让四个 if 语句中的两个起作用。不是 skaga 和 sabro..
      • 它有效,我只是没有检查最后两个分类法的两个首页。如此愚蠢的错误,但至少它起作用了。谢谢你的帮助本!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      相关资源
      最近更新 更多