Hice un código abreviado para mostrar el bucle en mi página de inicio personalizada:
function home_loop_shortcode() {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '8',
'cat' => '3, 6',
'orderby' => 'date'
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$postlink = get_permalink(get_the_ID());
$html="<li><a href="" . $postlink . '">' . get_the_title() . '</a></li>';
}
}
return $html;
wp_reset_postdata();
}
add_shortcode( 'loop', 'home_loop_shortcode' );
De hecho, tengo 8 publicaciones en las categorías ID 3 y 6, pero solo se muestra la primera publicación. El código está anidado dentro de este HTML:
<div class="home-loop">
<h3>Latest posts</h3>
<ul>
[loop]
</ul>
</div>
Incluso si elimino 'cat'
línea, o reemplazarlo por 'category_name' => 'foo'
o si configuro 'posts_per_page' => -1
, nada cambia. Probablemente me perdí algo obvio… ¡Ayuda!😭😅
estás sobrescribiendo $html
con la última publicación en lugar de concatenarla.
así que define $html="";
y luego concatenar:
function home_loop_shortcode() {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '8',
'cat' => '3, 6',
'orderby' => 'date'
);
$query = new WP_Query($args);
$html="";
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$postlink = get_permalink(get_the_ID());
$html .= '<li><a href="' . $postlink . '">' . get_the_title() . '</a></li>';
}
}
return $html;
wp_reset_postdata();
}
add_shortcode( 'loop', 'home_loop_shortcode' );
-
Creo que deberías usar el almacenamiento en búfer de salida.
– zillionera_dev
14 de noviembre a las 17:26
-
Sí, ese era el problema. Pensé que no era necesario si solo había una línea. Me equivoqué, aprendemos todos los días. Gracias.
– dragoweb
14 de noviembre a las 18:22
Krunal Bhimajiyani
Prueba este código:
Necesitas hacer una concatenación con $html.
function home_loop_shortcode() {
$html="";
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '8',
'cat' => '3, 6',
'orderby' => 'date'
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$postlink = get_permalink(get_the_ID());
$html .= '<li><a href="' . $postlink . '">' . get_the_title() . '</a></li>';
}
}
return $html;
wp_reset_postdata();
}
add_shortcode( 'loop', 'home_loop_shortcode' );