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

Cómo mostrar entradas recientes como desplegable en WordPress

Nota editorial: Ganamos una comisión de los enlaces de socios en WPBeginner. Las comisiones no afectan a las opiniones o evaluaciones de nuestros editores. Más información sobre Proceso editorial.

Probablemente conozcas el widget de categorías de WordPress. Recientemente, uno de nuestros lectores nos preguntó si era posible mostrar también entradas recientes en un desplegable. En este artículo, te mostraremos cómo mostrar entradas recientes como un desplegable en WordPress.

Add recent posts as drop down menu

¿Por qué y quién necesita entradas recientes en el menú desplegable?

WordPress viene con un widget de entradas recientes incorporado que puedes añadir a cualquier barra lateral o área preparada para widgets.

Este widget simplemente muestra una lista de entradas recientes, y puedes elegir el número de entradas que quieres mostrar. Pero si quieres mostrar más de 5-10 entradas, entonces la lista ocupará mucho espacio en tu barra lateral.

Algunos usuarios de WordPress pueden necesitar una forma compacta de mostrar entradas recientes. En ese caso, el uso de listas desplegables o cerrables puede ayudarle a ahorrar espacio.

Veamos un par de formas diferentes de mostrar entradas recientes como un menú desplegable en WordPress.

Mostrar entradas recientes de WordPress en un menú desplegable simple (código manual)

Este método usa la función integrada wp_get_recent_posts. Todo lo que necesitas hacer es copiar y pegar el siguiente código en el archivo functions. php de tu tema o en un plugin específico del sitio.

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

Ahora puedes usar el shortcode [SKX1 ] en tus entradas, páginas y widgets de texto de WordPress. Tendrá este aspecto:

Recent posts in a drop down menu on a WordPress site

Añadir Collapsible Entradas Recientes Usando Plugins

El método anterior simplemente lista tus entradas recientes en un formulario desplegable. Otra forma de ahorrar espacio es añadiendo un catálogo desplegable de entradas recientes que se amplía al hacer clic sobre él.

Lo primero que debe hacer es instalar y activar el plugin Collapse-O-Matic. Funciona de inmediato y no hay ajustes que deba configurar.

El plugin simplemente le permite mostrar cualquier cosa en un menú plegable usando un shortcode.

Antes de utilizar este plugin, necesitamos una manera de mostrar fácilmente entradas recientes en cualquier lugar que queramos. Simplemente añade este código al archivo functions. php de tu tema o a un plugin específico del sitio.

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

Este código simplemente le permite mostrar una lista de entradas recientes utilizando el shortcode [recentposts].

Ahora vamos a añadir nuestro shortcode en el Collapse-O-Matic shortcode para crear una lista plegable de entradas recientes.

Simplemente añada el shortcode así:

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

Puedes añadir este shortcode en un widget de texto, entradas o páginas de tu sitio WordPress. Así es como se ve en nuestro sitio de prueba.

Collapsable list of recent posts

Eso es todo, esperamos que este artículo te haya ayudado a mostrar entradas recientes como desplegables en WordPress. También puedes ver estos 6 consejos para crear un calendario editorial en WordPress.

Si te ha gustado este artículo, suscríbete a nuestro canal de YouTube para ver nuestros videotutoriales sobre WordPress. También puedes encontrarnos en Twitter y Facebook.

Descargo: Nuestro contenido está apoyado por los lectores. Esto significa que si hace clic en algunos de nuestros enlaces, podemos ganar una comisión. Vea cómo se financia WPBeginner , por qué es importante, y cómo puede apoyarnos. Aquí está nuestro proceso editorial .

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.

El último kit de herramientas de WordPress

Obtenga acceso GRATUITO a nuestro kit de herramientas - una colección de productos y recursos relacionados con WordPress que todo profesional debería tener!

Reader Interactions

17 comentariosDeja una respuesta

  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.

      Administrador

  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.

Deja tu comentario

Gracias por elegir dejar un comentario. Tenga en cuenta que todos los comentarios son moderados de acuerdo con nuestros política de comentarios, y su dirección de correo electrónico NO será publicada. Por favor, NO utilice palabras clave en el campo de nombre. Tengamos una conversación personal y significativa.