I have this code for the loop, and I need to exclude a category 4 from this loop. Any suggestions on how to achieve this?
Code that starts the loop
<?php if(have_posts()): ?>
<ol class="item_lists">
<?php
$end = array(3,6,9,12,15,18,21,24,27,30,33,36,39,42,45);
$i = 0;
while (have_posts()) : the_post();
$i++;
global $post;
?>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
you could use wp_parse_args() to merge your arguments into the default query
// Define the default query args
global $wp_query;
$defaults = $wp_query->query_vars;
// Your custom args
$args = array('cat'=>-4);
// merge the default with your custom args
$args = wp_parse_args( $args, $defaults );
// query posts based on merged arguments
query_posts($args);
although, i think the more elegant route is using the pre_get_posts() action. this modifies the query before the query is made so that the query isn’t run twice.
check out:
http://codex.wordpress.org/Custom_Queries#Category_Exclusion
based on that example to exclude category 4 from the index i’d put this in your functions.php:
add_action('pre_get_posts', 'wpa_44672' );
function wpa_44672( $wp_query ) {
//$wp_query is passed by reference. we don't need to return anything. whatever changes made inside this function will automatically effect the global variable
$excluded = array(4); //made it an array in case you need to exclude more than one
// only exclude on the home page
if( is_home() ) {
set_query_var('category__not_in', $excluded);
//which is merely the more elegant way to write:
//$wp_query->set('category__not_in', $excluded);
}
}
Method 2
From your functions file
function remove_home_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-4' );
}
}
add_action( 'pre_get_posts', 'remove_home_category' );
This code alters the query before the actual query is run so is the most efficient hook to modify the loop in this case.
Method 3
Before the line
<?php if(have_posts()): ?>
Insert something like this
<?php query_posts($query_string . '&cat=-4'); ?>
This excludes the category with Category ID 4. As seen here
Method 4
Adam is right. In addition, for pagination to work, you need to have something more like so:
<?php query_posts('post_type=post&paged='.$paged.'&cat=-4'); ?>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0