¿Cómo mostrar las últimas 3 publicaciones (publicaciones recientes) en una página estática?


Respuestas:


24

Usualmente uso este enfoque:

enfoque equivocado

<?php query_posts( array(
   'category_name' => 'news',
   'posts_per_page' => 3,
)); ?>

<?php if( have_posts() ): while ( have_posts() ) : the_post(); ?>

   <?php the_excerpt(); ?>
   <?php endwhile; ?>

<?php else : ?>

   <p><?php __('No News'); ?></p>

<?php endif; ?>

Con la ayuda de @swissspidy, la forma correcta es esta:

<?php 
   // the query
   $the_query = new WP_Query( array(
     'category_name' => 'news',
      'posts_per_page' => 3,
   )); 
?>

<?php if ( $the_query->have_posts() ) : ?>
  <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

    <?php the_title(); ?>
    <?php the_excerpt(); ?>

  <?php endwhile; ?>
  <?php wp_reset_postdata(); ?>

<?php else : ?>
  <p><?php __('No News'); ?></p>
<?php endif; ?>

Ver @codex para más información.


2
Me gusta hacer referencia a wordpress.stackexchange.com/a/1755/12404 para mostrar por qué usar query_posts()casi siempre es una mala idea.
swissspidy 01 de

4

Depende de lo que estés buscando. Si desea hacer una "página de publicaciones", es decir, crear un nuevo archivo de plantilla de página, puede crear un bucle secundario en esa página.

El códice tiene un ejemplo de esto y aquí hay otro ejemplo muy simplificado.

<?php
/*
Template Name: Page of Posts
*/
get_header(); 
?>

<?php while( have_posts() ): the_post(); /* start main loop */ ?>

    <h1><?php the_title(); ?></h1>

    <?php
        /* Start Secondary Loop */
        $other_posts = new WP_Query( /*maybe some args here? */ );
        while( $others_posts->have_posts() ): $other_posts->the_post(); 
    ?>
        You can do anything you would in the main loop here and it will
        apply to the secondary loop's posts
    <?php 
        endwhile; /* end secondary loop */ 
        wp_reset_postdata(); /* Restore the original queried page to the $post variable */
    ?>

<?php endwhile; /* End the main loop */ ?>

Si está buscando algo que pueda colocar en cualquier página, la mejor solución sería un código corto . Debería crear un código corto que recupere varias publicaciones y las devuelva en una lista (o lo que desee). Un ejemplo:

<?php
add_action( 'init', 'wpse36453_register_shortcode' );
/**
 * Registers the shortcode with add_shortcode so WP knows about it.
 */
function wpse36453_register_shortcode()
{
    add_shortcode( 'wpse36453_posts', 'wpse36453_shortcode_cb' );
}

/**
 * The call back function for the shortcode. Returns our list of posts.
 */
function wpse36453_shortcode_cb( $args )
{
    // get the posts
    $posts = get_posts(
        array(
            'numberposts'   => 3
        )
    );

    // No posts? run away!
    if( empty( $posts ) ) return '';

    /**
     * Loop through each post, getting what we need and appending it to 
     * the variable we'll send out
     */ 
    $out = '<ul>';
    foreach( $posts as $post )
    {
        $out .= sprintf( 
            '<li><a href="%s" title="%s">%s</a></li>',
            get_permalink( $post ),
            esc_attr( $post->post_title ),
            esc_html( $post->post_title )
        );
    }
    $out .= '</ul>';
    return $out;
}

¿Puedo poner esto en header.php o debería ponerlo en otro lugar?
user385917

El primer ejemplo puede ir a cualquier parte de su tema. El segundo ejemplo, shortcode, debería entrarfunctions.php
chrisguitarguy

el primer bloque de código no tiene un bucle en 3 publicaciones
Murhaf Sousli

3

Hay una guía para este caso preciso en el codex de WordPress. Véalo aquí : pego el código aquí porque es bastante corto, para obtener más información, visite el sitio wordpress.org.

<?php
$args = array( 'numberposts' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ($postslist as $post) :  setup_postdata($post); ?> 
    <div>
        <?php the_date(); ?>
        <br />
        <?php the_title(); ?>   
        <?php the_excerpt(); ?>
    </div>
<?php endforeach; ?>

1

Wordpress proporciona una función para ese tipo de solicitud: query_posts () .

query_posts () es la forma más fácil de alterar la consulta predeterminada que WordPress usa para mostrar publicaciones. Use query_posts () para mostrar publicaciones diferentes a las que normalmente se mostrarían en una URL específica.

Por ejemplo, en la página de inicio, normalmente vería las últimas 10 publicaciones. Si desea mostrar solo 5 publicaciones (y no le importa la paginación), puede usar query_posts () de esta manera:

query_posts ('posts_per_page = 5');

Una vez que haya realizado la consulta, puede mostrar las publicaciones de la manera que desee.


-1
<?php $the_query = new WP_Query( 'posts_per_page=3' ); 
while ($the_query -> have_posts()) : $the_query -> the_post();?>
<?php /*html in here etc*/ the_title(); ?>
<?php endwhile;wp_reset_postdata();?>

su código que responde a la pregunta: ¿Cómo mostrar las últimas 3 publicaciones (publicaciones recientes) en una página estática? ¿Te ayudaría si dijera: "Usualmente uso este enfoque:"?
Jon
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.