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

Så här visar du senaste inlägg som en rullgardinsmeny i WordPress

Du är förmodligen bekant med widgeten Category i WordPress. Nyligen frågade en av våra läsare oss om det var möjligt att också visa senaste inlägg i en rullgardinsmeny. I den här artikeln kommer vi att visa dig hur du visar senaste inlägg som en rullgardinsmeny i WordPress.

Add recent posts as drop down menu

Varför och vem behöver senaste inlägg i rullgardinsmeny?

WordPress levereras med en built-in senaste inlägg widget som du kan add to någon sidebar eller widget redo area.

Denna widget visar helt enkelt en lista över senaste inlägg, och du kan välja hur många inlägg du vill visa. Men om du vill visa mer än 5-10 posts, kommer listan att ta mycket plats i din sidebar.

Vissa användare av WordPress kan behöva ett kompakt sätt att visa de senaste inläggen. I så fall kan du spara utrymme genom att använda rullgardinsmenyer eller minimerbara listor.

Låt oss ta en titt på ett par olika sätt att visa senaste inlägg som en rullgardinsmeny i WordPress.

Visa senaste inlägg i WordPress i en vanlig rullgardinsmeny (manuell kod)

Den här metoden använder den built-in wp_get_recent_posts-funktionen. Allt du behöver göra är att copy and paste följande kod i ditt temas functions.php-fil eller ett site-specifikt plugin.

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');

Nu kan du använda shortcode [rp_dropdown] i dina WordPress-poster, pages och textwidgets. Det kommer att se ut så här:

Recent posts in a drop down menu on a WordPress site

Lägga till minimerbara senaste inlägg med plugin

Ovanstående metod listar helt enkelt dina senaste inlägg i en rullgardinsmeny. Ett annat sätt att spara utrymme är att lägga till en minimerbar lista över senaste inlägg som förstoras när användare klickar på den.

Det första du behöver göra är att installera och aktivera tillägget Collapse-O-Matic. Det fungerar direkt från boxen och det finns inga inställningar för dig att konfigurera.

Pluginet tillåter dig helt enkelt att visa vad som helst i en minimerbar meny med hjälp av en shortcode.

Innan vi använder detta plugin behöver vi ett sätt att enkelt visa senaste inlägg var vi vill. Lägg helt enkelt till den här koden i ditt temas functions.php-fil eller ett site-specifikt plugin.

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');

Denna kod tillåter dig helt enkelt att visa en lista över senaste inlägg med hjälp av shortcode [recentposts].

Nu ska vi add to vår shortcode i Collapse-O-Matic shortcode för att skapa en minimerbar lista över senaste inlägg.

Lägg helt enkelt till shortcoden så här:

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

Du kan add to denna shortcode i en text widget, posts eller pages på din WordPress site. Så här såg det ut på vår testsite.

Collapsable list of recent posts

Det var all, vi hoppas att den här artikeln hjälpte dig att visa senaste inlägg som rullgardinsmeny i WordPress. Du kanske också vill se dessa 6 tips för att skapa en fantastisk redaktionell kalender i WordPress.

Om du gillade den här artikeln, vänligen prenumerera på vår YouTube-kanal för WordPress video tutorials. Du kan också hitta oss på Twitter och Facebook.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

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.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

17 kommentarerLämna ett svar

  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.

      Administratör

  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.

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.