• 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/

  • 相关阅读:
    选择屏幕加功能码
    alv 列标题
    指针引用的学习
    CM3中数据传输对齐/非对齐方式
    perl学习笔记之:模式匹配,模块,文档
    PERL学习之模式匹配
    perl:split函数用法
    perl:_DATA_ _LINE_ _FILE_
    CVS update常用技巧
    cvs 文件无法上传debug
  • 原文地址:https://www.cnblogs.com/ytkah/p/11926186.html
Copyright © 2020-2023  润新知