Welcome to CodeCrew Infotech

shape shape
Shape Shape Shape Shape
Blog

How To Show Recent Post As A Dropdown In WordPress

WordPress's post comes in Recent Post Widget, you can add it in Widget Block or Sidebar.

This widget block shows you which posts are currently added. But if your post is more than 10-15, it will take up more space for it.

So you can show more than 10-15 posts with the help of this dropdown plugin or manual code of the dropdown.

 

1. Add Dropdown With Manually Code:

Step 1: First of all Copy the below code in the paste function.php file.

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

 

Step 2: After pasting, the code goes to the Appearance > Widget and copy the below shortcode and paste it to the recent post widget.

[rp_dropdown]

 

Step 3: Refresh your site and see the recent block of Sidebar. The recent block would have been changed in the dropdown.

 

2. Add Dropdown using the plugin:

Step 1: First of all install and activate the Collapse-O-Matic plugin.

 

Step 2: There is no change in this plugin after activating the plugin. Then go to the theme editor form appearance and find the function.php file then copy the below code and paste it into this file.

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

 

Step 2: Now go to the Appearance > widget from the WordPress dashboard.

If you display a post in list type then copy the below code and paste the Recent post block.

[recentposts]

 

 You can see your post is displayed in list type.

 

If you display a post in dropdown type then copy the below code and paste the Recent post block.

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

 

You can see your post is displayed in dropdown type.