Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Simple shortcode turning overcomplicated

<?php
function recent_posts() {

$q = new WP_Query( 
  array( 'orderby' => 'date', 'posts_per_page' => '1') 
);

$list = '<ul>';

while($q->have_posts()) : $q->the_post();
//$location = bloginfo('template_directory');
$imgsrc = get_post_meta($q->ID, 'blog-left-image', true);

$list .= '<li><a href="' . get_permalink() . '">' . get_the_title();
$list .= '<img src="' . $location . '/image.php/resized.jpg?width=80&amp;height=80&amp;image=' . $imgsrc . '" alt="" class="related-posts-img" style="float:left; margin-right:5px;" />';
$list .= '</a></li>';

endwhile;

wp_reset_query();

return $list . '</ul>';

add_shortcode("recent_posts", "recent_posts");?>

Thought this would be straightforward. Want to create a shortcode to display the post thumbnails. Problem is, the get_post_meta(...) outputs nothing and the bloginfo('template_directory') doesn't concatenate correctly.

share|improve this question

2 Answers 2

up vote 0 down vote accepted

Looks like you've got two issues:

The first is your use of $q->ID. This is not the correct way to get the current post id from inside a loop. You want to use get_the_ID().

The second issue is you should be using get_bloginfo() instead of bloginfo(). Bloginfo echo's the data directly while get_bloginfo() returns it (allowing you to assign to the $location variable).

One last suggestion: get_bloginfo('template_directory') is not going to be changing values in each iteration of your loop. You can move that line outside of the loop to save some resources.

share|improve this answer
    
Thank you! I knew I was close. –  frankV Mar 7 '12 at 5:33

maybe?

function recent_posts() {

$args = array ( 'orderby' => 'date', 'posts_per_page' => '1');

$recent_posts = get_posts($args);

if($recent_posts) :
$list = '<ul>';

//store the $post variable
global $post; $temp = $post;
foreach ($postslist as $post) :  setup_postdata($post); 

$imgsrc = get_post_meta(get_the_ID(), 'blog-left-image', true);

$list .= '<li><a href="' . get_permalink() . '">' . get_the_title();
$list .= '<img src="' . get_template_directory_uri() . '/image.php/resized.jpg?width=80&amp;height=80&amp;image=' . $imgsrc . '" alt="" class="related-posts-img" style="float:left; margin-right:5px;" />';
$list .= '</a></li>';

endwhile;

$list .= '</ul>';
//reset the $post variable
$post = $temp;
endif;

return $list;

add_shortcode("recent_posts", "recent_posts");
share|improve this answer
    
Thanks for your help too @helgatheviking –  frankV May 25 '12 at 17:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.