Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coppa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Come escludere l’ultimo articolo dal loop dei post di WordPress

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

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.

How to exclude latest post from the WordPress post loop

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:

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.

Adding custom code snippets to WordPress

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.

Adding a custom code snippet to your WordPress website using WPCode

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”.

Excluding latest blog from the WordPress post loop

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”.

Automatically inserting code into a WordPress website

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.

Excluding latest blog from the WordPress post loop using WPCode

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.

Bluehost site settings

Andate ora alla sezione Collegamenti rapidi.

Quindi, fai clic sul pulsante “File Manager”. Bluehost mostra anche la directory principale del sito web, se necessario.

Accessing a website's file manager in Bluehost

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”.

Opening the index.php file in Bluehost file manager

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:

Adding code to exclude the latest post in Bluehost file manager

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.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

42 commentiLascia una risposta

  1. 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!

  2. 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:

  3. 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;

  4. 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

  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.

  6. 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!

        • 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()

  7. 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

  8. 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. :(

  9. 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!

  10. 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!

      • 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!

        • 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 :)

  11. 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 :)

    • 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

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.