wordpress調用自定義post_type文章


  前面我們講了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', 'posts_per_page' => 10);
                                    $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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM