Reputation: 39
I have next code for show latest post in wordpress. I want to add thumbnail and date. Any suggestion?
function last_article($atts){
extract(shortcode_atts(array(
'posts' => 1,
), $atts));
$return_string = '<ul>';
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
endif;
$return_string .= '</ul>';
wp_reset_query();
return $return_string;
}
Upvotes: 0
Views: 135
Reputation: 9951
Your shortcode is pure evil. You should never ever use extract()
. extract()
is to be completely removed from Wordpress core. This should also tell you something how really bad extract()
really is. See the corresponding trac ticket here
Also, never ever use query_posts
.
Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination).
You should be using WP_Query
You should visit the Shortcode API in the codex and see how to properly construct a shortcode
With this all in mind, your code should look something like this
function last_article($atts){
$a = shortcode_atts( array(
'posts' => 1,
), $atts );
$return_string = '<ul>';
$q = new WP_Query(array('orderby' => 'date', 'order' => 'DESC' , 'posts_per_page' => $a['posts']));
if ($q->have_posts()) {
while ($q->have_posts()) {
$q->the_post();
$return_string .= '<li>'.the_date().'</li>';
$return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
if (has_post_thumbnail()) {
$return_string .= '<li>'.the_post_thumbnail().'</li>';
}
}
}
$return_string .= '</ul>';
wp_reset_postdata();
return $return_string;
}
Upvotes: 1
Reputation: 6080
Try this :
function last_article($atts){
extract(shortcode_atts(array(
'posts' => 1,
), $atts));
$return_string = '<ul>';
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string .= '<h4>'.the_date().'</h4>';
$return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
if (has_post_thumbnail()) {
$return_string .= '<div>'.the_post_thumbnail().'</div>';
}
endwhile;
endif;
$return_string .= '</ul>';
wp_reset_query();
return $return_string;
}
Upvotes: 1