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 mostrare i post recenti come menu a tendina in 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.

Probabilmente conoscete il widget Categoria di WordPress. Recentemente, uno dei nostri lettori ci ha chiesto se fosse possibile visualizzare anche i post recenti in un menu a tendina. In questo articolo vi mostreremo come mostrare i post recenti in un menu a tendina in WordPress.

Add recent posts as drop down menu

Perché e a chi servono i post recenti in drop down?

WordPress è dotato di un widget per i post recenti che si può aggiungere a qualsiasi barra laterale o area predisposta per i widget.

Questo widget visualizza semplicemente un elenco di post recenti e potete scegliere il numero di post che volete mostrare. Tuttavia, se volete mostrare più di 5-10 post, l’elenco occuperà molto spazio nella vostra barra laterale.

Alcuni utenti di WordPress potrebbero aver bisogno di un modo compatto per visualizzare i post recenti. In questo caso, l’utilizzo di elenchi a discesa o pieghevoli può aiutare a risparmiare spazio.

Vediamo un paio di modi diversi per mostrare i post recenti come menu a discesa in WordPress.

Mostrare i post recenti di WordPress in un semplice menu a discesa (codice manuale)

Questo metodo utilizza la funzione integrata wp_get_recent_posts. Tutto ciò che dovete fare è copiare e incollare il seguente codice nel file functions.php del vostro tema o in un plugin specifico del sito.

function wpb_recentposts_dropdown() { 
$string .= '<select id="rpdropdown">
			<option  value="" selected>Select a Post</option>';

$args = array( 'numberposts' => '5', 'post_status' => 'publish' );

$recent_posts = wp_get_recent_posts($args);
	foreach( $recent_posts as $recent ){
		$string .= '<option value="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</option> ';
	}

$string .= '</select>
			<script type="text/javascript"> var urlmenu = document.getElementById( "rpdropdown" ); urlmenu.onchange = function() {
      		window.open( this.options[ this.selectedIndex ].value, "_self" );
 			};
			</script>';

return $string;
} 
add_shortcode('rp_dropdown', 'wpb_recentposts_dropdown');
add_filter('widget_text','do_shortcode');

Ora è possibile utilizzare lo shortcode [rp_dropdown] nei post, nelle pagine e nei widget di testo di WordPress. L’aspetto sarà questo:

Recent posts in a drop down menu on a WordPress site

Aggiunta di post recenti collassabili tramite plugin

Il metodo precedente elenca semplicemente i post recenti in un modulo a discesa. Un altro modo per risparmiare spazio è aggiungere un elenco pieghevole di post recenti che si espande quando gli utenti vi fanno clic.

La prima cosa da fare è installare e attivare il plugin Collapse-O-Matic. Funziona subito e non ci sono impostazioni da configurare.

Il plugin consente semplicemente di mostrare qualsiasi cosa in un menu pieghevole utilizzando uno shortcode.

Prima di utilizzare questo plugin, abbiamo bisogno di un modo per mostrare facilmente i post recenti ovunque vogliamo. È sufficiente aggiungere questo codice al file functions.php del tema o a un plugin specifico per il sito.

function wpb_recentposts() { 

$string .= '<ul>';
$args = array( 'numberposts' => '5', 'post_status' => 'publish' );
$recent_posts = wp_get_recent_posts($args);
	foreach( $recent_posts as $recent ){
		$string .= '<li><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a></li> ';
	}
$string .= '</ul>';
return $string;
} 
add_shortcode('recentposts', 'wpb_recentposts');
add_filter('widget_text','do_shortcode');

Questo codice consente semplicemente di visualizzare un elenco di post recenti utilizzando lo shortcode [recentposts].

Ora aggiungeremo il nostro shortcode allo shortcode Collapse-O-Matic per creare un elenco collassabile di post recenti.

È sufficiente aggiungere lo shortcode in questo modo:

[expand title="Recent Posts"][recentposts][/expand]

È possibile aggiungere questo shortcode in un widget di testo, nei post o nelle pagine del sito WordPress. Ecco come appare sul nostro sito di prova.

Collapsable list of recent posts

Questo è tutto, speriamo che questo articolo vi abbia aiutato a mostrare i post recenti a tendina in WordPress. Potreste anche voler vedere questi 6 consigli per creare un calendario editoriale di successo in WordPress.

Se vi è piaciuto questo articolo, iscrivetevi al nostro canale YouTube per i video tutorial 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

17 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. Yvonne Manders says

    Hi,

    I installed the collapse-o-mattic and pasted the code in the functions.php file.
    After that I pasted the shortcode [expand title=”Recent Posts”][recentposts][/expand] in a textwidget, but nothing happened.
    Am I missing something?

    Best regards, Yvonne

    • WPBeginner Support says

      You would want to place the shortcode in the text editor rather than the visual editor to ensure you don’t have styling blocking the shortcode from working.

      Admin

  3. Erika says

    Line 3 has an error. The closing option tag is missing its closing “/”. This is generating a blank option in the menu.

  4. Amjad says

    Hi there. I have used above code to show all my posts in a drop down but its not sorted. I have two questions here:
    1. How can i sort posts by title?
    2. How can i show posts of a specific category in dropdown instead of showing all posts?

  5. Rolando says

    Nice article! How can you make it by a specific category and not just all your categories? Also, can it be done alphabetical?

  6. Farai Mugaviri says

    Thank you so much for the great help there. I wouldalso want to display categories in a dop-down list, if you can help with that…. But now what if I update my WordPress, is it even possible? I saw somewhere they talked about challengess when updating the wordpress and risking losing data because of hardcoding the PHP functions

  7. Robert says

    Great tool, thanks for that!
    Is it possible to sort the post output in the list in alphabetical order?
    Thanks in advance for your reply!

    Regards,
    Robert

  8. Andre says

    Its possible to show the posts dropdown with a button to submit?

    ‘function wpb_recentposts_dropdown() {
    $string .= ‘
    Select your School’;

    $args = array( ‘numberposts’ => ‘5’, ‘post_status’ => ‘publish’ );

    $recent_posts = wp_get_recent_posts($args);
    foreach( $recent_posts as $recent ){
    $string .= ” . $recent[“post_title”].’ ‘;
    }

    $string .= ‘
    FIND SCHOOL NOW
    var urlmenu = document.getElementById( “submitschool” ); urlmenu.onclick = function() {
    window.open( this.options[ this.selectedIndex ].value, “_self” );
    };
    ‘;

    return $string;
    }
    add_shortcode(‘rp_dropdown’, ‘wpb_recentposts_dropdown’);
    add_filter(‘widget_text’,’do_shortcode’);’

  9. NG SHAIKH says

    It is an excellent article. Beginners like me can understand power of WordPress and its plug-ins by such articles.

    I would be enlightened if some articles are written to display a message on specific page and not on all posts and pages.

    It will also help beginners if a few articles are written to display a form for user entry which can be saved in the database

  10. Julie S says

    I really like the drop-down menu of recent posts. How can I control the width of this drop down menu? It defaults too long for my sidebar.

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.