Cum să creezi un shortcode pentru afișarea ultimelor 2 postări
Doresc să creez un shortcode care afișează ultimele 3 postări pe orice pagină...
Ar trebui să arate astfel:
Titlu
Rezumat...Citește mai mult
Am adăugat acest cod în functions.php
function my_recent_post()
{
global $post;
$html = "";
$my_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 2
));
if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
$html .= "<h2>" . get_the_title() . " </h2>";
$html .= "<p>" . get_the_excerpt() . "</p>";
$html .= "<a href=\"" . get_permalink() . "\" class=\"button\">Citește mai mult</a>";
endwhile; endif;
return $html;
}
add_shortcode( 'recent', 'my_recent_post' );
Și funcționează, dar acum pagina principală afișează cele 2 postări dorite într-un div, iar problema este că sub conținut, adică sub div-ul cu shortcode, afișează întregul al doilea articol (vezi imaginea).
Ce sugestii aveți?
Adaugă wp_reset_postdata()
după bucla ta while
:
endwhile;
wp_reset_postdata();
endif;
Acest lucru va asigura că, după ce shortcode-ul tău rulează, postarea actuală curentă este restaurată, astfel încât orice tag-uri de șablon să afișeze datele corecte.

introduceți codul aici
text îngroșat vă rog să încercați aceasta
function my_recent_post()
{
global $post;
$html = "";
$my_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 2
));
if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
$html.= get_template_part( 'content', 'excerpt' );
endwhile; endif;
return $html;
}
add_shortcode( 'recent', 'my_recent_post' ); ?>
**<h1>creați un fișier php content-excerpt.php și plasați-l în tema dumneavoastră</h1>
codul acestui fișier este**
<article id="post-<?php the_ID(); ?>">
<header class="entry-header">
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
</div>
</header>
<div class="entry-excerpt">
<?php the_excerpt(); ?>
</div>
<a href="<?php get_permalink() ?>" class="button">Citește mai mult</a>
</article>

Cum va funcționa asta? get_template_part
va afișa conținutul, nu îl va returna.
