Am avut de facut o mica functie de curand la un site si a trebuit sa afisez cele mai recente 3 articole de pe blog printr-un shortcode API WordPress. Iata mai jos codurile folosite.
add_shortcode( 'lastposts', 'post_list_shortcode' );
function post_list_shortcode( $atts ) {
ob_start();
$wp_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 3,
'order' => 'ASC',
'orderby' => 'title',
) );
if ( $wp_query->have_posts() ) { ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post('post-home'); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h3 class="titlupost"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<?php endif; ?>
<?php
$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 25 );
echo $trimmed_content;
?>
</div>
<?php endwhile;
wp_reset_postdata(); ?>
<?php $lastpost = ob_get_clean();
return $lastpost;
}
}
Pentru folosire in editor se foloseste [lastposts]. Se vor afisa cele mai recente 3 articole cu thumbnail.
Se pot modifica parametri pentru a afisa mai multe articole ‘posts_per_page’ => 3 se poate schimba numarul pentru a afisa mai multe articole.
UPDATE CODE:
Un alt programator a facut un cod mult mai bun si il pun aici pentru folosire.
define( "MY_PLUGIN_SHORTCODE_LAST_POSTS", "lastposts" );
add_shortcode( 'MY_PLUGIN_SHORTCODE_LAST_POSTS', 'post_list_shortcode' );
function post_list_shortcode( $atts ) {
$args = shortcode_atts( [
'post_type' => 'post',
'posts_per_page' => 3,
'order' => 'ASC',
'orderby' => 'title',
], $atts, 'MY_PLUGIN_SHORTCODE_LAST_POSTS' );
$post_list = get_posts( $args );
if( empty( $post_list ) )
return '';
$response = '';
foreach( $post_list as $post ) {
$response .= '<div id="post-' . $post->ID . '" class="' . implode( ' ', get_post_class( 'post-home', $post->ID ) ) . '">';
$response .= '<h3 class="post-title"><a href="' . get_permalink( $post ). '">' . get_the_title( $post ). '</a></h3>';
if( has_post_thumbnail( $post ) ) {
$response .= '<a href="' . get_permalink( $post ). '">';
$response .= get_the_post_thumbnail( $post );
$response .= '</a>';
}
$response .= get_the_excerpt( $post );
$response .= '</div>';
}
return $response;
}
Pentru folosire se pune acest code [MY_PLUGIN_SHORTCODE_LAST_POSTS]