I've been trying to display recent posts for months excluding the current category. I have already researched on several forums and almost everything on StackOverflow and unfortunately I did not achieve success on my project.
I need help with the following functions:
My recent posts work normally. I can delete the current post and display all others.
What I would like to do is display all the latest posts excluding the current category.
Examples:
My categories: example1 / example2 / example3 /
Let's say the user is viewing this link:
Link 1 =
domain.com/category/example1/examplepost
In recent posts I would like to display the last 5 posts from the category "example2" and "example3".
Link 2 =
domain.com/category/example2/examplepost
In recent posts I would like to display the last 5 posts from the category "example1" and "example3".
I have the following code that I use in function.php
add_action('pre_get_posts', 'wpa_12345' );
function wpa_12345( $wp_query ) {
$excluded = array(5);
if( !is_admin() ) {
$wp_query->set('category__not_in', $excluded);
}
}
add_filter('pre_get_posts', 'exclude_category');
This code allows me to delete a category that I choose.
I would like some code that would automatically identify the current category to exclude from recent posts.
I followed Abhik user's guidelines ... See if the code was assembled correctly in functions.php
function wpa_12345( $wp_query ) {
//Get the current category ID
$catID = get_queried_object_id();
//Pass it to the Query arguments
$args = array(
//Your other arguments here
'category__not_in' => array($catID),
);
$excluded_posts = new WP_Query($args);
if( !is_admin() ) {
$wp_query->set('category__not_in', $excluded);
}
}
add_filter('pre_get_posts', 'exclude_category');
Even reassembling the code, I didn't get what I expected.