在自定义循环中每x个帖子插入一个帖子类型

时间:2014-03-20 17:13:04

标签: php wordpress loops

我希望有人可以帮我解决这个问题。

我正试图用两种不同的帖子类型('产品'和'服装')在wordpress中制作一个循环

以下代码工作正常,输出最新订购的两种帖子类型的列表。

    $loop = new WP_Query( array( 
                'post_type' => array( 'product', 'outfits' ),
                'posts_per_page' => 15
              ) ); 
            $counter = 0;
            ?>
            <?php if ( $loop->have_posts() ) { while ( $loop->have_posts() ) { $loop->the_post();
            $counter++; ?>
            <?php $loop->is_home = false; ?>
            <?php
                $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large');
                $titulo = get_the_title();
                $content = apply_filters ('the_content', $post->post_content); ?>
              <div class="caja-<?php echo $counter; ?>">

                <?php if ( $post->post_type == "product" ) {            
                    //some stuff
                <?php } else { 
                    //some stuff
                } ?>

            </div>
            <?php } } wp_reset_postdata();

我想做的是在X服装之后插入产品发布类型。

我试图合并我在其他问题中发现的类似解决方案,但没有运气。我不是一个PHP专家,所以任何帮助表示赞赏

    <?php
    $args = array('post_type'=>'post', 'posts_per_page'=>9, 'category_name'=>'news');
    $posts = get_posts($args);

    $args = array('post_type'=>'testimonials', 'posts_per_page'=>3);
    $testimonials = get_posts($args);

   // see how many of the regular posts you got back //
   $post_count = count($posts);
   // see how many testimonials you got back //
   $testimonial_count = count($testimonials);
   // add them up to get the total result count //
   $total_count = $post_count + $testimonial_count;

   // Loop through the total number of results //
   for($i = 1; $i <= $total_count; $i++){

   // assuming you want to show one testimonial every third post //
   if($i % 3 == 0){
   // this means you're on the a third post, show a testimonial //
    setup_postdata($testimonials[$i]);
   }
   else{
    /** show a regular post */
   setup_postdata($posts[$i]);
   }
  /** and now handle the output */
  ?><h1><?php the_title();?></h1><?php

 } ?>

1 个答案:

答案 0 :(得分:2)

$x = 3;
$products = get_posts(array(
    'post_type' => 'product',
    'posts_per_page' => -1
));

$outfits = get_posts(array(
    'post_type' => 'outfit',
    'posts_per_page' => -1
));

foreach ($outfits as $num => $outfit) {
    if ( ($num+1) % $x == 0) {
        if (isset($products[($num+1)/$x - 1])) {
            array_splice( $outfits, $num, 0, array($products[($num+1)/$x - 1]) );    
        }
    }
}

foreach ($outfits as $outfit) {
    $posts_id[] = $outfit->ID;
}

$query = new wp_query(array(
    'post_type' => array('outfit', 'product'),
    'post__in' => $posts_id,
    'posts_per_page' => 15,
    'orderby' => 'post__in'
));