0
votes

I have a normal loop that outputs posts based on the given $args. After three posts I want to insert a post that is from a Featured category. I've tried starting a new WP_Query, simple query_posts in different combinations. Nothing seems to work. Any ideas why ?

$args = array(
    'post_type' => 'post', 
    'posts_per_page' => $count,
    'paged' => $paged,
    'page' => $paged,
    'cat' => $cat,
    'ignore_sticky_posts' => 1
);

// create a new instance of WP_Query
$my_query = new WP_Query($args);

<ul>
<?php 
$i = 0;
if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); 

 if($i == 3): ?>
    <li> //insert here one post from featured category
    </li>
<?php endif; ?>

<li>
// the normal query stuff is here
</li>
<?php $i++ //post counter
endwhile; //end loop while
endif; //end loop 
?>
</ul>
1
So any other way to get a post inside the loop, expect using the get_post() which works but needs the exact id ? - CiprianD
when you do the_post() you should be able to access and set anything from the $post variable. So run your feature query first and set the contents of that featured item in its own variable, like $featured = $post - then in your conditional $i == 3 you can say $feature->post_title, get_permalink($feature->ID) etc. You don't have to run the loop inside another loop. - Kai Qing

1 Answers

0
votes

I did it this way. Before the main query I did a special query for the featured post.

$args2 = array(
        'post_type' => 'post', 
        'posts_per_page' => 1,
        'category_name' => 'TheCategoryName-Slug',
        'ignore_sticky_posts' => 1
);

$my_query2 = new WP_Query($args2);
$post_ids = array(); //create an array to store the ids of the posts
if ($my_query2->have_posts()) : while ($my_query2->have_posts()) : $my_query2->the_post();
  $post_ids[] = get_the_ID();
 endwhile;
 wp_reset_postdata();
endif;

After you have all the ids you can use them to get the data you need. Basically, all the data from the wp_posts table (http://codex.wordpress.org/Database_Description#Table:_wp_posts). The post author is returned as an id that can be used to get the name using get_userdata() function.

echo get_post_field('post_title', $post_ids[0]);
echo get_post_field('post_author', $post_ids[0]);
echo get_post_field('post_date', $post_ids[0]);