There are a few errors which I want to address
First of all, you should never use query_posts
to construct custom queries. This is not just my emphasis, but the codex as well. The one big problem with query_posts
is, it many circumstances, pagination fails
Note: This function isn’t meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination).
Secondly, never run unnecessary queries where it is not needed. The main query can very easily be modified with the use of pre_get_posts
, which saves on unnecessary database queries being performed by the use of custom queries
This hook is called after the query variable object is created, but before the actual query is run.
Thirdly, if you don’t have a choice, and you have to run custom queries, do it with WP_Query
or get_posts
instead of query_posts
Also, you are abusing php tags. It is not necessary to open and close php tags after each piece of code, unless you are switching between php and html. For instance
</div>
</div>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>
</div>
can be rewritten as
</div>
</div>
<?php
endwhile;
else :
endif;
?>
</div>
This is how I will tackle the problem. I do not say it is the best solution, but it is a better and cleaner method to achieve your goal
Your first query for your featured content should look something like this
<section id="blog-posts">
<header class="header-sezione">
<h2>Articoli in evidenza</h2>
</header>
<?php
$featured = new WP_Query('tag=featured');
if ($featured->have_posts()) :
while ($featured->have_posts()) : $featured->the_post(); ?>
<---YOUR LOOP ELEMENTS--->
<?php
endwhile;
wp_reset_postdata();
endif;
?>
Your main loop is fine as is, I will not change anything to that. DO NOT use a custom query here to exclude a tag. Use pre_get_posts
to do that. Here is how
In your functions.php, add the following code to remove posts from the featured tag from the main query on your home page. You will be using the is_home()
conditional tag to target the home page
EDIT
I forgot to include this. Is is always fail safe to include a check to see if you are not on a admin page (!is_admin()
). The reason being, pre_get_posts
alters the main query which is used both on front end and backend, thus all changes will be seen front end and back end. You just want to make changes on front end, so the modified code will be
function exclude_featured_tag( $query ) {
if ( !is_admin() && $query->is_home() && $query->is_main_query() ) {
$query->set( 'tag__not_in', array('ID OF THE FEATURED TAG') );
}
}
add_action( 'pre_get_posts', 'exclude_featured_tag' );