Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How can I modify my query in order to exclude certain posts by slug? Is it possible?

query_posts(array('category_name' => 'Mycat', 'posts_per_page' => -1));

Ty

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You can get the post ID from the slug with the url_to_postid() function:

$ID = url_to_postid(slug);

then just exclude the ID from your query:

query_posts(array('category_name' => 'Mycat', 'posts_per_page' => -1, 'post__not_in' => $ID ));

You can create an array of post IDs if you need to exclude multiple pages.

share|improve this answer
    
Did not know about url_to_postid. Ty very much –  webmasters Jul 25 '12 at 13:21
    
Upvote for the url_to_postid() to get the post ID from the slug, but using query_posts() is the wrong implementation. –  Chip Bennett Jul 25 '12 at 13:59

Do not use query_posts()!. Filter pre_get_posts instead *.

<?php
function wpse59617_filter_pre_get_posts( $query ) {
    // Only modify the main query
    if ( ! $query->is_main_query() ) { return $query; }
    // Get the ID of the post to exclude
    $slug = 'some-post-slug';
    $post_id = url_to_postid( $slug );
    // Modify the query
    $query->set( 'category_name', 'Mycat' );
    $query->set( 'post__not_in', $post_id );
    $query->set( 'posts_per_page', '-1' );
    // Return the modified query
    return $query;    
}
add_filter( 'pre_get_posts', 'wpse59617_filter_pre_get_posts' );
?>

* No, really: don't use query_posts(). Here's why.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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