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

Cómo ordenar entradas por fecha de caducidad 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.

En el pasado, hemos compartido cómo caducar entradas en WordPress usando el plugin Post Expirator. Bueno, al crear un sitio de anuncios / catálogo / ficha de eventos, encontramos este plugin para ser súper útil. Podemos borrar fácilmente los anuncios / catálogos / fichas de eventos que han caducado. En segundo lugar, gracias a este plugin, es muy fácil ordenar las entradas por fecha de caducidad también. En este artículo, le mostraremos cómo ordenar entradas por fecha de caducidad en WordPress.

Código Actualizado para reflejar los cambios en el plugin donde cambiaron el nombre del campo personalizado. Gracias Tajim por hacérnoslo saber en los comentarios.

En nuestro proyecto en particular, teníamos Eventos como un tipo de contenido personalizado. Ahora bien, esto es para una organización sin fines de lucro que tiene como un evento por mes, así que simplemente creamos un bucle para poner en su página de eventos. Usted puede utilizar el código en su barra lateral, o en cualquier otro lugar que desee.

$args = array( 'post_type' => 'event', 'posts_per_page' => 15, 'order' => 'ASC', 'meta_key' => '_expiration-date', 'orderby' => 'meta_value' );
$eventloop = new WP_Query( $args );
if ( $eventloop->have_posts() ) : while ( $eventloop->have_posts() ) : $eventloop->the_post();

//All the Loop Content Goes Here


El truco es utilizar la meta_key y luego user oderby meta_value. Poniéndolo en orden ascendente muestra el evento que viene pronto (caduca más pronto). Ejemplo de nuestro anuncio / catálogo / ficha de eventos:

Sort Posts by Post Expiration (Event Example)

Nota para que esto funcione, DEBE usar el plugin Post Expirator.

Si usted tiene alguna pregunta, no dude en preguntar en los comentarios a continuación.

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 .


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

25 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. Francis Waller says

    Hi, I’m trying to get this work on my woo commerce products which have to manipulated to be offsite courses which expire on a certain date. I really need to sort them by expiry date not sure what I’m doing wrong. Thanks

  3. dtp says

    Is it possible to show the posts that end till next day or next week, month and so on.
    I want to create a site thats shows all posts that are ending next day. and one which is shwoing all post that are ending next week.

    Any suggestions?

  4. James Parkin says

    I have been trying to get this code to work with a Genesis Pro child theme. Made several posts with future dates. Add this code to sidebars via short codes and tried inside the functions.php file. Not using any custom fields or adding info.

    Any ideas would be appeciated

  5. James says

    I have been trying to get this to work to no avail. posted it in sidebar, function.php and as short codes. Any help would be appreciated.

  6. James says

    I have not been able to get this to work with a Genesis Pro child theme. Added it to the last lines of the function.php file. added meta values too. unsure why it does not post in ASC order by expiration date.

    thank you in advanced

  7. JP says

    Posts like this are why I love the internet (and blogs like yours). This is exactly what I was looking for and couldn’t have been laid out more simply. Thanks!

  8. Tajim says

    Just wanted to say that in current version of this plugin the custom field name has changed from
    expiration-date to _expiration-date.

    The custom field is hidden. So please update the code above.


  9. Steve Combes says

    Thanks for the great post.

    If I wanted to echo the post expiration date in the loop what code might I use?

      • Adam says

        I changed it to ‘_expiration-date’ and I’m getting the data, but how would you re-sort this into the correct date display? My date is March 1st 2015 and what’s echoed is “1425254340”


    • Editorial Staff says

      This article is not for total beginners. Because you have to have fair understanding of how WordPress themes work in order to make this code work with your specific theme.


      • CuriousObserver says

        If this isn’t for beginners, why did you post it to I, too, am having difficulty inserting this into my blog and would like to see an answer to KITSTS’ question.

        • Editorial Staff says

          Here at WPBeginner, we define beginners into various levels. Beginner blogger aka total beginner (just starting to blog, doesn’t know what is RSS, FTP etc). Beginner theme designer (knows HTML+CSS, but has no idea how to build themes in WordPress). Beginner plugin developer (knows the general concept around programming, but not specific to WordPress).

          The reason why we can’t answer KITST’ question is because it is impossible to answer with the information provided. The code shared in the article is a standard WordPress loop. Where you paste it in your theme will vary based on your needs and also the type of theme you are using.

          If you are using a child theme, then most likely that code will end up in your functions.php file, so you can hook it into the function provided by the theme framework.

          If you are using another WordPress theme, then the code can go in various different template files (index.php, sidebar.php, archive.php, archive-{posttype}.php, footer.php, header.php, etc). Each theme is organized differently which makes it impossible for us to give you an exact location where to paste this code.

          Also note, that the loop that we shared above is from an example work that we created using a custom post type called events. You may not want to use it for a custom post type events. Perhaps you want to use it for a different post type called deals.

          This article was intended for beginner theme designers and/or beginner developers who are looking for an easy way to do this.

  10. G J says

    I was wondering, which plugin is used for displaying the upcoming events in the example above?
    Thanks for a lovely article…

      • G J says

        Ahhh..ok, is it possible for you to give an example on “All the Loop Content Goes Here” I am updating the webpage of a NGO and kind of liked this way of displaying the events on. As you may have noticed I am a beginner so I would really appreciate your help ;o)….

        • Editorial Staff says

          The loop code essentially is the_title(); php tag to show the title. Another custom field to show the date. The loop is explained pretty well here:

          We used styling (div/images/css) to make it look that way. This post is about how to sort posts by expiration date, and the article shows just that. The example used is something that we did for our client, so unfortunately we cannot share the images/styling that they paid for. Send us an email if you are interested in having us do this for you. We have special non-profit rates.

  11. Jacko says

    This is a cool feature.  There are several situations where this is what you need to be doing.
    This website has one of my favorite designs.  The #IBCT is about finding the best blogger in the world. Your website has made it to the semis.

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.