I want to hide posts that belong to a particular category on homepage and let it display only in sidebar.
I can successfully hide posts on homepage but I can't display it in the sidebar.
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-14' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' ){
How can I go about it?
You can create shortcode and add it in sidebar this will work for you. Follow the steps as: In your function.php add following code:
function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array( 'category_name' => 'announcements', 'posts_per_page' => 10 ) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbycategory widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</a></li>';
} else {
// if no featured image is found
$string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
}
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts', 'wpb_postsbycategory');
// Enable shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');
Now Add [categoryposts] shortcode in the text widget and save it.
This might work for you...
create a sidebar.php with this code
<aside role="complementary">
//Display your Post here
<?php if ( is_active_sidebar( 'sidebar1' ) ) : ?>
<?php dynamic_sidebar( 'sidebar1' ); ?>
<?php endif; ?>
</aside>
And then you can add the sidebar like this in your page:
<?php get_sidebar( 'sidebar1' ); ?>
To display a particular post of a category u can do it like this:
<aside role="complementary">
<?php
$args = array (
'post_type' => 'annonce',
'tax_query' => array (
array(
'taxonomy' => 'annonce_category',
'field' => 'slug',
'terms' => array( 'Tanzpartner gesucht', 'Tanzpartnerin gesucht' ),
'operator' => 'IN',
),
),
);
$query = new WP_Query( $args );
?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
.....
<?php if ( is_active_sidebar( 'sidebar1' ) ) : ?>
<?php dynamic_sidebar( 'sidebar1' ); ?>
<?php endif; ?>
A simple way could be using this plugin ( https://wordpress.org/plugins/display-posts-shortcode/ ). It queries the posts based on different characteristics (category included). It works through the use of shortcodes.