【割とよくやるWPのTips - 其の一】【Single/Loop】投稿に紐付いてるタームを配列に格納しWP-queryの条件に加える

  
    <?php // (single/loop)投稿に紐付いてるタームを配列に格納しWP-queryの条件に加える
      //タクソノミースラッグを指定
      $taxSlug = 'タクソノミー ';
    
      //投稿に紐付けられたタームを取り出す処理
      $customPostTerms = wp_get_object_terms($post->ID, $taxSlug);
      if(!empty($customPostTerms)){
        if(!is_wp_error( $customPostTerms )){
          //配列の箱を宣言
          $termList = [];
          foreach($customPostTerms as $term){
            //ループが終わるまでタームスラッグを配列に足していく
            $termList[] = $term->slug;
          }
        }
      }
    ?>
    <?php
      $args = array(
        'paged' => $paged,
        'post_type' => '投稿タイプ',
        'posts_per_page' => -1,
        'no_found_rows' => true,
        'post_status' => 'publish',
        'tax_query' => array(
          array(
            'taxonomy' => $taxSlug,//タクソノミースラッグ
            'field' => 'slug',
            'terms' => $termlist,//上記で配列に格納したタームスラッグを指定する。
          ),
        ),
      );
      ?>
    <?php $wpquery = new WP_Query( $args );
    //->WP Query.....
    ?>
  

自分のブログにもかこーっと。

あと、頭丸めました、超寒い!

SNSシェア

WP TECH WordPress技術専門 Tips

コーポレートサイトへ

WP TECH WordPress技術専門 Tips

採用サイトへ