Si vuole escludere l’ultimo articolo dal loop di WordPress?
Nascondendo l’articolo più recente, si ha la libertà di mostrare questo contenuto in altre posizioni del sito web. Potete anche aggiungere il vostro stile in modo che l’ultimo articolo risalti sempre sulla homepage e sugli archivi del blog.
In questo articolo vi mostreremo come escludere l’ultimo articolo dal loop di WordPress.
Perché escludere l’ultimo articolo dal loop dei post di WordPress?
Di default, WordPress visualizza gli articoli del blog ai visitatori in ordine cronologico inverso, per cui gli articoli più recenti appaiono per primi. Tuttavia, è possibile modificare l’aspetto dell’ultimo articolo sulla homepage personalizzata o sulla pagina dell’archivio di WordPress.
Escludendo l’ultimo articolo dal loop di WordPress, è possibile mostrare il contenuto in una posizione diversa e persino aggiungere uno stile personalizzato.
Detto questo, vediamo come nascondere l’ultimo articolo del blog escludendolo dal loop di WordPress. Utilizzate i collegamenti rapidi qui sotto per passare direttamente al metodo che desiderate utilizzare:
Metodo 1: Utilizzo del plugin WPCode (consigliato)
Il modo più semplice per escludere l’ultimo articolo dal loop è aggiungere del codice al sito web di WordPress.
Alcune guide vi diranno di modificare manualmente i file del tema, ma questo può causare errori comuni di WordPress e può anche rompere completamente il vostro sito web.
Per questo motivo, vi consigliamo di utilizzare WPCode. È il miglior plugin per gli snippet di codice che consente di aggiungere facilmente codice personalizzato in WordPress senza mettere a rischio il sito.
Per prima cosa, è necessario installare e attivare il plugin gratuito WPCode. Per ulteriori informazioni, consultare la nostra guida passo-passo su come installare un plugin per WordPress.
Una volta attivato il plugin, andare su Code Snippets ” Add Snippet.
Qui vengono mostrati tutti gli snippet preconfezionati che è possibile aggiungere al proprio sito. Tra questi c’è uno snippet che consente di disabilitare completamente i commenti, di caricare tipi di file che WordPress di solito non supporta, di disabilitare le pagine dell’allegato e molto altro ancora.
Ora è possibile passare del mouse sull’opzione “Aggiungi codice personalizzato (nuovo snippet)” e fare clic sul pulsante “Usa snippet” quando appare.
Nello schermo successivo, digitate un titolo per lo snippet di codice. Questo è solo per referer, quindi si può usare qualsiasi cosa si voglia.
Quindi, si deve aprire il menu a discesa “Tipo di codice” e scegliere “Snippet PHP”.
A questo punto, è sufficiente incollare quanto segue nell’editor del codice:
<?php
function wpsites_exclude_latest_post( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'offset', '1' );
}
}
add_action( 'pre_get_posts', 'wpsites_exclude_latest_post', 1 );
Quindi, scorrere giù la pagina fino alla sezione “Pannello di inserimento”.
Se non è già selezionata, scegliere “Inserimento automatico” e “Esegui ovunque”.
Infine, scorrere fino all’alto dello schermo e fare clic sul dispositivo di scorrimento “Inattivo” in modo che appaia “Attivo”.
Quindi, fai clic sul pulsante “Salva snippet” o “Aggiorna” per rendere attivo lo snippet di codice.
Ora, se si visita il sito web di WordPress, l’ultimo articolo del blog sarà nascosto.
Metodo 2: Modifica dei file del tema di WordPress (senza plugin richiesti)
Note: Questa esercitazione funziona solo con i temi classici di WordPress, poiché i temi a blocchi hanno una serie di file diversi. Se utilizzate un tema a blocchi, vi consigliamo di utilizzare il primo metodo.
Si consiglia inoltre di eseguire prima il backup del sito web e/o di utilizzare un ambiente di staging per evitare errori quando si segue questo metodo.
Un altro modo per escludere l’ultimo articolo dal loop di WordPress è aggiungere del codice ai file del tema di WordPress.
Si ottiene un risultato simile a quello del codice precedente, ma è necessario aggiungerlo direttamente al loop di WordPress dove si vuole che venga visualizzato.
Ad esempio, se si vuole cambiare il loop degli articoli sul sito web, è necessario aggiungere il codice al file index.php
.
Tenete presente che l’aggiunta di codice direttamente ai file di WordPress può potenzialmente causare problemi con la paginazione sul vostro blog WordPress.
Per prima cosa, è necessario aprire il file manager del fornitore di hosting WordPress o collegare il sito web con un client FTP.
Per questo tutorial, utilizzeremo il file manager di Bluehost, in quanto il processo è molto più semplice rispetto all’utilizzo di un FTP. Detto questo, i passaggi sono più o meno gli stessi sia che si utilizzi un FTP che un altro host web.
Se siete utenti di Bluehost, accedete alla dashboard del vostro account di hosting e navigate nella scheda “Siti web”. Quindi, fate clic su “Impostazioni” del sito web che desiderate modificare.
Andate ora alla sezione Collegamenti rapidi.
Quindi, fai clic sul pulsante “File Manager”. Bluehost mostra anche la directory principale del sito web, se necessario.
Una volta entrati nel file manager, è necessario individuare il file che si desidera modificare. Supponiamo di voler aggiungere il codice a index.php
, allora lo troverete nella cartella del tema corrente, che si trova all’interno di public_html/wp-content.
Una volta lì, basta cliccare con il tasto destro del mouse sul file index.php e fare clic su “Modifica”.
Ora è necessario copiare il codice seguente e aggiungerlo al loop di WordPress:
query_posts('posts_per_page=6&offset=1');
Questo codice indica al loop di mostrare solo i 5 articoli successivi a quello più recente.
È necessario aggiungere il codice direttamente sopra il loop di WordPress, in modo che abbia un aspetto simile al frammento di codice qui sotto:
<?php
query_posts('posts_per_page=6&offset=1');
if ( have_posts() ) {
// Load posts loop.
while ( have_posts() ) {
the_post();
get_template_part( 'template-parts/content/content', get_theme_mod( 'display_excerpt_or_full_post', 'excerpt' ) );
}
// Previous/next page navigation.
twenty_twenty_one_the_posts_navigation();
} else {
// If no content, include the "No posts found" template.
get_template_part( 'template-parts/content/content-none' );
}
Ecco come appare il nostro codice nel file manager di Bluehost:
Una volta aggiunto il codice, è sufficiente fare clic sul pulsante “Salva modifiche”.
Quindi, procedete con l’anteprima del vostro sito web WordPress.
Speriamo che questo articolo vi abbia aiutato a capire come escludere l’ultimo articolo dal loop di WordPress. Potreste anche voler consultare la nostra guida su come fare soldi online facendo blog con WordPress o le nostre scelte di esperti per i migliori builder di pagine WordPress trascina e rilascia.
Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.
Syed Balkhi says
Hey WPBeginner readers,
Did you know you can win exciting prizes by commenting on WPBeginner?
Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
You can get more details about the contest from here.
Start sharing your thoughts below to stand a chance to win!
George says
This piece of code has helped solved 90% of an issue on my blog.
WPBeginner Support says
Glad to hear our code was able to help
Admin
ghazali says
Is there anyway for me to remove only top 3 featured post from the homepage?
ivan logan says
How to remove all posts without featured images(thumbnails), I have 9000 to remover them!
Praveen says
Thanks, Good job, Good Solution
Matt says
Beauty post! Simple, clear, and VERY handy. Cheers to you!
Dimarj says
Thanks for this.
BGH_ says
Hey guys, thanks for this article! I want to implement this, but whenever I try I’ve got an strange problem: entries would look like exactly like the frontpage, showing a list of recent post rather than the post itself. My code is slightly different, since is a SMTheme. Any help will be much appreciated. PS: Sorry for posting twice, but the code has printed wrong. Here you go:
space says
Solution is work fine, Thanks. but pagination broke after applying this code, I have tried but not able to work with correct pagination. Any solution to pagination ? .
Rickie Anand says
apply class to the li as per the number of page and a counter & give style to p1c1 as display:none;
Sabi Maharjan says
I have used two plugins. One is “Recent facebook post” to show recent posts in wprdpress and “Facebook publish page” to publish my wordpress posts in facebook . Now I want exclude the recent post of the facebook that was already posted from my wordpress posts .
How can I do it ?
WPBeginner Support says
For that your plugin posting content from your Facebook page should have a check to see if a post was already published from WordPress to Facebook. We do not recommend users to directly edit plugin files. However, if you are comfortable editing php files then you can fork the plugin as a new plugin and then add the code to accomplish this.
Admin
Pastor Wynn says
Thanks for the great tip. I had spent hours trying to figure this out, and you made it so simple!
Gu-ens says
Thanks a lot.
the ‘post__not_in’ option does not work in wordpress 3.5
Jim says
Hmm, when i tried this code on a category page loop, it couldn’t keep the posts for only that category, instead it acted as if it was the front page loop and displayed all posts.
Amin says
Thank you so much man! This helped a lot!
Regards!
Fernando says
Thanks a lot!! very usefull tip!
GangeshMatta says
Thanks!
PabloCovarrubias says
hello, i just have one question, when i do this, pagination doesen0t work anymore, how can i fix this?
thanks, other than that, it works perfectly!!
cheers!
space says
Yes, pagination not working. you have found any working solution for pagination, I am still searching ..
Kev Bowman says
Did you ever find a solution for this?
de hams says
pagination do not work on index page most so we can make out own ajax pagination call and mostly query_posts() works for pagination rather then WP_Query()
Jon says
Thanks so much for this! I couldn’t figure it out at all but this worked perfectly.
Wordpwess says
Is there a way to offset a post from one cat?
E.g I want to show all posts apart from the LATEST post of category x
Editorial Staff says
Yes, you can just select category_in parameter, and add your category ID.
Admin
Luka says
Thanks mate, you save my day
Khurram says
“query_posts(‘posts_per_page=6&offset=1’);” this is not worked for me , while i am using the WP-PageNavi plugin for page navigation.
Editorial Staff says
what error are you getting?
Admin
Ken says
Thanks for the info. Worked well Though, I’m encountering another issue for another site I’m currently doing. Is there a way to exclude from the loop only the latest post of a particular category?
Thing is, I’ve a blog that publishes podcasts. The front page highlights the most recent podcast – posts are published under category: Podcast – via its own styling. At the same time, the front page also shows the last 5 most recent posts, of which may include posts under the category “podcast”. I just don’t want to show in the loop the most recent post published under “Podcast” simply because it’s already featured with it’s own styling. Hope you can help me out. thanks!
Editorial Staff says
You can exclude all posts from the category “postcast” from your loop if you want. But there is no simple way of excluding just the latest post.
Admin
Joffrey says
Thanks for the tip!
But I was wondering if there is also a way to exclude the post that is currently showed on screen.
If yes, can you tell me how to do this?
Thanks in advance!
Editorial Staff says
Don’t really understand your question? Which screen?
Admin
Joffrey says
One of my pages displays first of all the latest or current post the user is viewing.
The current post is called by the loop.
Below this post I want to display the excerpts of other previous posts without the current post displayed in this list.
The previous post-excerpts are called by query_posts:
query(‘showposts=3&cat=5’);
while($previousPosts->have_posts()) : $previousPosts->the_post();
?>
As you can see I call 3 posts(excerpts) from category 5 which displays three posts from category News. This seems ok but within these 3 post-excerpts, the current post which is called by the loop is also in this list.
Do you know a way to exclude the current post within this list?
Thanks again!
Editorial Staff says
You can add offset=1 in the query to skip the first post.
Joffrey says
Thanks again for the quick response!
However, I did try the offset=1 in the query, only thing is that when you press an older post, you get to see the older post in the main loop, within the list excerpts the latest post is excluded, but the older post which is now the current post is still in the excerpts list.
Any idea how to exclude not the latest but the current post?
Thanks so far already
Editorial Staff says
Email us the live link to the site, so we can see exactly whats going on. Use the contact form for email.
Bilal Ahmed says
Thank you so much for this piece as i was looking for a way to exclude 4 latest posts form my home page and i got answer by this articles and i have replaced (query_posts(‘posts_per_page=6&offset=1’);) by query_posts(‘posts_per_page=6&offset=3’); and its done
Jeremy says
Where exactly do you put this code to remove al posts but the sticky on the main page.
Thanks,
Editorial Staff says
That is a multi-step process. First you would need to have a custom page template. Second you would need to create that custom page, your front page. Then you would run a query on that custom template showing only sticky posts.
Admin
dominik says
Thanks, it was exactly what I was looking for! Thanks for any other hints.
Morning Copy says
Thanks for this. Nice solution for magazine-style layouts.