最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

templates - How to insert "get_template_part()" based on Category ID?

programmeradmin3浏览0评论

I am trying to insert a part of my template into a Category Archive page.

How would I go about that?

I guess I'd need something like this:

   <?php
    $catarray = get_the_category( $post->ID );
    foreach ($catarray as $cat) {
        $catid = $cat->term_id;

        if ($catid == 10) {
          get_template_part('1','2') << ? 
        }
        if ($catid == 7) {
          get_template_part('3','4') << ?
        }

    }
    ?>

I am trying to insert a part of my template into a Category Archive page.

How would I go about that?

I guess I'd need something like this:

   <?php
    $catarray = get_the_category( $post->ID );
    foreach ($catarray as $cat) {
        $catid = $cat->term_id;

        if ($catid == 10) {
          get_template_part('1','2') << ? 
        }
        if ($catid == 7) {
          get_template_part('3','4') << ?
        }

    }
    ?>
Share Improve this question asked Jan 28, 2022 at 2:12 HenryHenry 9831 gold badge8 silver badges31 bronze badges 4
  • - and would it need an ELSE statement at the end? – Henry Commented Jan 28, 2022 at 2:15
  • As written, your code is going to look for files named 1-2.php (then 1.php) and 3-4.php (then 3.php) in your theme. Also, to answer the else question: you'd need an else statement if you want to set a default template-part to load (ie if $catid is neither 7 nor 10). – Pat J Commented Jan 28, 2022 at 2:20
  • Thanks @PatJ - so basically there appears nothing wrong with my code? – Henry Commented Jan 28, 2022 at 2:29
  • Aside from the <<? text, which I assume were meant as pointers for us to look at and not actual parts of your code. – Pat J Commented Jan 28, 2022 at 3:19
Add a comment  | 

1 Answer 1

Reset to default 0

I think the best way is hooking to the filter template_include https://developer.wordpress.org/reference/hooks/template_include/

You'll find some exmple at https://markjaquith.wordpress.com/2014/02/19/template_redirect-is-not-for-loading-templates/

发布评论

评论列表(0)

  1. 暂无评论