0

Any help would be greatly appreciated!

I have a Custom Post Type 'video', with a taxonomy 'tax-video' and I'm looping through posts in the sub-taxonomy term 't-o-t-w'. I need to exclude the latest/most recent post.

I've been searching around for a couple hours trying different things, but still don't really even know where to start. Here's what I've tried, but it breaks the page:

    <?php

    //trying to get the recent post
    $tip = get_terms('t-o-t-w','orderby=id&order=DESC&number=1');
    $latest_tip = $tip[0]->ID;

    $args = array(
    'post_type' => 'video',
    'tax_query' => array(
        array(
            'taxonomy' => 'tax-video',
            'field'    => 'slug',
            'terms'    => 't-o-t-w',
             ),
          ),
    'posts_per_page' => '8',
       //Trying to Exclude it here
    'post__not_in' => array( $latest_tip ),
    );

    $query = new WP_Query( $args ); ?>  

    <?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>

    //code to be executed

    <?php endwhile; endif; wp_reset_postdata(); ?>
  • Remove "php " from the beginning of the last line. – Gabriel May 26 '16 at 18:41
  • Oops, I had accidentally deleted some parts of my code. I updated it so it's valid now. Thanks – BradH May 26 '16 at 19:42
  • Notes: it's usually faster to exclude a post in PHP manually than it is to use post__not_in, which can sometimes cause performance issues. Your wp_reset_postdata will always be called even if no postdata is set ( calls to the_post() ), move it inside the if statement just after the while loop. You may be able to avoid the query entirely by using the taxonomy archive that comes with WordPress, and the theme file taxonomy-tax-video.php, if so, use pre_get_post to modify the query, rather than creating an whole new one – Tom J Nowell May 26 '16 at 20:27
  • Also, get_terms returns term objects, not posts, so your post__not_in is being passed a term ID, not a post ID. If it worked as you expected you'd be excluding the wrong post that just happened to have the same ID – Tom J Nowell May 26 '16 at 20:29
1

wp_query has the offset parameter which you can use to skip posts, e.g.

$args = array(
 'post_type' => 'video',
 'tax_query' => array(
  array(
   'taxonomy' => 'tax-video',
   'field'    => 'slug',
   'terms'    => 't-o-t-w',
  ),
 ),
 'posts_per_page' => '8',
 'offset' => 1, // excludes the first post in the query
);

you may just be over thinking this

  • Yep that did the trick! Thanks Gareth. I had tried the offset earlier with this syntax 'posts_per_page' => '6&offset=1', I had seen, but it didn't work ... and then I moved on to other nonsense apparently. Much Appreciated! – BradH May 26 '16 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.