wordpress調用自定義post_type文章

  • 2019 年 11 月 26 日
  • 筆記

  前面我們講了wordpress添加post_type自定義文章類型,我們現在來講一下如何把自定義文章調用出來,我們以product為例,雖然我們自定義好了 Post Type 同時也編寫了一些內容,但是在首頁、列表裡面並沒有顯示出來。自定義的 Post Type 的內容不會自動混入主循環裡面。那如何讓自定義 Post Type 的內容顯示出來?需要使用 pre_get_posts 這個 action 來做一些處理:

function add_custom_pt( $query ) {    if ( !is_admin() && $query->is_main_query() ) {      $query->set( 'post_type', array( 'post', 'the_custom_pt' ) );    }  }  add_action( 'pre_get_posts', 'add_custom_pt' );

  將上面的程式碼加入到主題function.php文件中

  第二步,上面操作依賴模板,如果需要高度自定義或者在頁面的某個模組中調用列表,就需要用到 WP_Query 類來調用:

<?php $args = array( 'post_type' => 'product');                                      $loop = new WP_Query( $args );                                      while ( $loop->have_posts() ) : $loop->the_post(); ?>                                              <div class="col-4">                                                  <a href="<?php the_permalink(); ?>" class="item wow zoomIn">                                                          <b><?php the_title(); ?></b>                                                      </div>                                                  </a>                                              </div>                                          <?php endwhile; ?>                                          <?php                                          the_posts_pagination( array(                                              'mid_size'  => 2,                                              'prev_text' => __( 'Prev', 'textdomain' ),                                              'next_text' => __( 'Next', 'textdomain' ),                                          ) );                                          ?>

  新建archive-product.php模板放在主題目錄,這個是product的post_type模板,將上面的程式碼加入到archive-product.php中進行調用文章,刷新快取就可以看到了

  參考資料:https://developer.wordpress.org/reference/hooks/pre_get_posts/

https://blog.wpjam.com/article/wordpress-post-type/