You can add this code to a new file named wpsites.php and then use the template tag directly in any file or hook it in using a custom function with theme specific or WordPress hooks.
Note: All code can be used in a child theme.
<?php
// Your Custom Query Arguments
$args = array(
'category__not_in' => array( 007 )
) );
$wpsites_catposts = new WP_Query( $args );
// Your Custom Loop
if ( $wpsites_catposts->have_posts() ) {
echo '<div class="primary-sidebar"><ul>';
while ( $wpsites_catposts->have_posts() ) {
$wpsites_catposts->the_post();
echo '<li><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . get_the_title() . '</a></li>';
}
echo '</ul></div>';
} else {
echo '<div class="primary-sidebar">No posts found for this query.</div>';
}
wp_reset_postdata();
Get Template Part
Add this code in any template file. For this question, one of your sidebar.php files.
<?php get_template_part( 'wpsites' ); ?>
Custom Function
Or hook it in if your theme includes action hooks:
add_action ( 'your_themes_before_sidebar_hook', 'exclude_posts_in_sidebar_loop' );
function exclude_posts_in_sidebar_loop() {
if ( is_home() ) {
get_template_part( 'wpsites' );
}}
Change the conditional tag in the above custom function to suit your own needs.
Alternative Method For Query
Rather than use the arrays of $args, you can replace Your Custom Query Arguments with this line:
$wpsites_catposts = new WP_Query( array(
'category__not_in' => array( 007 )
) );