El loop (bucle) es una de los componentes mas importantes de nuestro WordPress. Nos permite tomar las noticias de la base de datos para luego imprimirlas en nuestra plantilla. Haciendo uso de pequeños cambios en este elemento, podemos obtener resultados asombrosos: obtener una única entrada, incluir publicidad en determinados post y mucho más.
En este artículo, original de SmashingMagazine, os mostraré 6 formas de modificar el loop de WordPress para hacer de nuestros blogs más poderosos.
1. Obtener un post definido entre dos fechas
Simplemente tendremos que sustituir las fechas deseadas, conservando el formato AÑO -MES – DÍA, en este código:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php
function filter_where($where = '') {
$where .= " AND post_date >= '2009-03-17' AND post_date <= '2009-05-03'";
return $where;
}
add_filter('posts_where', 'filter_where');
query_posts($query_string);
while (have_posts()) :
the_post();
the_content();
endwhile;
?> |
2. Utiliza más de un loop por página sin que se dupliquen tus post
Empecemos por el primer loop. Lo primero que deberemos hacer es introducir esté código en nuestro apartado de noticias destacadas. Este mostrará los 8 post más recientes.
1 2 3 4 5 6 7 8 9 | <?php
query_posts('showposts=8');
$ids = array();
while (have_posts()) : the_post();
$ids[] = get_the_ID();
the_title();
the_content();
endwhile;
?> |
Ahora aplicaremos este otro código en nuestro segundo loop, mostrará todos los post sin incluir los mostrados en nuestro primer loop:
1 2 3 4 5 6 7 | <?php
query_posts(array('post__not_in' => $ids));
while (have_posts()) : the_post();
the_title();
the_content();
endwhile;
?> |
3. Insertar publicidad después del primer post
Muy sencillo de aplicar, tan solo tendremos que pegar el siguiente código en el loop y añadir nuestra publicidad en la línea 6:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php if (have_posts()) : ?>
<?php $count = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?>
<?php if ($count == 2) : ?>
//Pon aquí tu publicidad
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php else : ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?> |
4. Obtener un post de un campo personalizado con un valor específico
Pegaremos este código en el loop y modificaremos los valores del meta_key (campo) y del meta_value (valor del campo) por los deseados.
1 2 3 | <?php query_posts('meta_key=KEY&meta_value=VALUE'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?> |
5. Lista de próximos post
Este sencillo código mostrará los post que tengamos marcados para que sean publicados en una determinada fecha (opción de WordPress). Podremos modificar el número de post que queramos mostrar modificando el valor del showposts por el que deseemos.
1 2 3 4 5 6 7 | <?php query_posts('showposts=10&post_status=future'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<span class="datetime"><?php the_time('j. F Y'); ?></span></p>
<?php endwhile;
else: ?><p>No future events scheduled.</p>
<?php endif; ?> |
6. Mostrar post publicados hace un año
El código toma la fecha actual y busca en la base de datos referencias de hace justamente un año. Muy útil para blogs con cierta antigüedad.
1 2 3 4 5 6 7 8 9 10 11 | <?php
$current_day = date('j');
$last_year = date('Y')-1;
query_posts('day='.$current_day.'&year='.$last_year);
if (have_posts()):
while (have_posts()) : the_post();
the_title();
the_excerpt();
endwhile;
endif;
?> |
En el artículo original de SmashingMagazine muestran 4 formas más de modificuar nuestro loop de WordPress, podeis echarle un vistazo en el siguiente enlace.
Enlace: 10 Usefull WordPress Loop Hacks