Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Need Loops WordPress

I need a couple template loops created...

I already have loops created but am trying to really clean up my code to make it easier for me to make changes in the future and my code is a little convoluted due to me working with themes and customizing by copying/pasting things that I figure out as I go along.

Here are the loops I need:

Loop #1 - 3 most recent posts not tagged "featured"

Loop #2 - The most recent post tagged "featured" and category "sports"

Loop #3 - 15 more most recent posts that doesn't include the posts from Loop #1

I don't need any stylized or anything like that. Just need an example to make sure I'm doing things right on my end and something that will show me how to add more loops if needed over time.

Thanks!

Answers (2)

2014-12-30

Arnav Joy answers:

For first you can use


$args = array(
'tag__not_in' => 'post_tag', //must use tag id for this field
'posts_per_page' => 3);


For second you can use


$args = array(
'category__and' => 'sports',
'tag__in' => 'post_tag', //must use tag id for this field
'posts_per_page' => 5);



for point 3 you can use 'post__not_in' => array($post_ids) , where $post_ids you can retrieve from the loop of point 1

2014-12-30

Fahid Javid answers:

Hi,

1) For the first loop you can fetch your posts something like this:


$term = get_term_by( 'slug', 'featured', 'post_tag' ); // get term by slug
$args = array(
'tag__not_in' => array( $term->term_id ),
'post_type' => 'post',
'posts_per_page' => 3
);


2) For the second loop you can go with this:


$args = array(
'tag ' => 'featured',
'category_name ' => 'sports',
'post_type' => 'post',
'posts_per_page' => 1
);


3) You can use an array to collect the post ids of first loop declaring right after the_post(); function of the first loop.

Example: $exclude_posts[] = $post->ID;

After that you can use that array to exclude posts of first loop from the third loop using the following code:


$args = array(
'post__not_in ' => $exclude_posts,
'post_type' => 'post',
'posts_per_page' => 15
);


Regards,

Fahid


Brennen Jones comments:

Thanks! I think that both of you responses helped. I'm just taking the time to clean up my loops. It's a long process.