【问题标题】:Wordpress show multiple post types in loopWordpress 循环显示多种帖子类型
【发布时间】:2015-04-08 11:35:45
【问题描述】:

我正在创建一个 Wordpress 网站,我想在首页上显示包含该网站内容的“图块”。这些磁贴是来自网站的自定义帖子类型,例如“我们的服务”、“顾问”、“博客帖子”等。

我知道如何在 Wordpress 中显示一种自定义帖子类型,但问题是我需要在同一个循环中提取多个帖子类型,因为我希望它们显示在矩阵中。另一个问题是我需要以随机顺序对所有项目进行洗牌,例如,并非所有博客都只显示在一个地方,而是所有对象随机显示在不同项目之后。

第三个问题是我需要显示某个帖子类型的所有项目,而只显示另一个帖子类型的最新项目。例如,我是否需要显示所有“我们的服务”图块,但只显示几个“博客”图块。

这可以做到吗,或者你不能用这种方式使用Wordpress提取记录吗?

感谢您的帮助!

【问题讨论】:

    标签: php wordpress loops custom-post-type


    【解决方案1】:

    我建议阅读自定义 wordpress 查询 https://codex.wordpress.org/Class_Reference/WP_Query

    第一个问题你只需要指定

    'post_type' => array( 'tiles', 'consultants', 'post' )
    

    第二个问题

    'orderby' => 'rand'
    

    所以你会有类似的东西

    $args = array(
      'post_type' => array( 'tiles', 'consultants', 'post' ),
      'orderby'   => 'rand'
    );
    $query = new WP_Query( $args );
    

    对于第三个问题 - 我不确定是否可以通过一个查询来实现。

    【讨论】:

      【解决方案2】:

      你可以自定义这样的东西,

        $posttypes = array('post_typ1','post_typ2','post_typ3');
         $randompost_typs = shuffle($posttypes);
        $counter = count($posttypes);
        for($i=0; $i<$counter;$i++) {
             // suppose you want to show all posts from post_type1 then
             if($randompost_typs[$i]=='post_typ1') {
                   $posts_per_page = -1;
                } elseif($randompost_typs[$i]=='post_typ2') { // will work for 2nd post type
                   $post_per_page = 5; // show 5 posts from this post type
                } else {
                    $post_per_page = 3; // show 3 posts from last post type
                }
                // here you will use the WP_Query class from wordpress 
                 $args = array(
                     'post_type' => $posttypes[$i],
                      'orderby'   => 'rand',
                       'posts_per_page' => $post_per_page
                      );
                 $query = new WP_Query( $args );
                 if($query->have_posts()) : while($query->have_posts()): $query->the_post();
                  // all the remaining wp loop content for example
                  the_title();
                  the_excerpt();
                  endwhile;
                  else:
                   echo 'no posts';
                  endif;
             }
      

      希望这会有所帮助,如果有任何问题,请告诉我。

      【讨论】:

      • 谢谢,这似乎就是我要找的!但是,这些帖子并不是完全随机显示的,而是分块显示的。例如,首先是所有 post_type1,然后是所有 post_type2。我希望它们完全改组,以便您得到:post_type1、post_type2、post_type3、post_type1。这可能吗?
      • 检查更新的答案,只需将shuffle() 用于帖子类型数组
      • 帖子类型仍然相互显示,我希望列表中的帖子类型不同而不相同
      • 这是一个想法,在每个循环中将发布数据保存在一个数组中,然后随机化该数组,然后再通过 1 个循环打印
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多