0

I am trying to turn a custom query into a shortcode but I am having some difficulty. Firstly, I am not sure how to return a custom thumbnail size via $return_string...in fact I am not sure how to return most of my styling. here is what I have so far.

I'd like to put this:

<?php $query = new WP_Query
            (array('showposts' => 3, 'orderby' => 'date', 'order' => 'DESC'));
            while ($query->have_posts()) : $query->the_post();?>
                <div class="recent_post">
                    <div class="recent_title">          
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </div>
                    <div class="recent_img">
                        <?php the_post_thumbnail('recent_news_size'); ?>
                    </div>
                    <div class="recent_excerpt">
                        <?php echo excerpt(22); ?>
                    </div>
                </div>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); ?>

Into my shortcode here:

function recent_posts_function($atts){
   extract(shortcode_atts(array(
      'posts' => 1,
   ), $atts));

   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
   if (have_posts()) :
      while (have_posts()) : the_post();
         $return_string .= '//put stuff here';
      endwhile;
   endif;

   wp_reset_query();
   return $return_string;
}

function register_shortcodes(){
   add_shortcode('recent-posts', 'recent_posts_function');
}

add_action( 'init', 'register_shortcodes');

Do any of you gurus know of a quick and easy way to turn it all into a shortcode?

0

This should do the trick: http://codex.wordpress.org/Shortcode_API#Output

Copying verbatim from the documentation:

function myShortCode() {
    ob_start();
    ?> <HTML> <here> ... <?PHP
    return ob_get_clean();
}

Basically what happens is that all your HTML will not be output, but rather stored in an "output buffer", and returned by the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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