-1

I wrote a script to display recent posts from a specific category in wordPress.

<?php
$catquery = new WP_Query( 'cat=3&posts_per_page=10' );
while($catquery->have_posts()) : $catquery->the_post();
?>
<ul>
<li><h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>

<ul><li><?php the_content(); ?></li>
</ul>
</li>
</ul>
<?php endwhile; ?>

Now I want to make a short code for this code because I want to display recent categories in pages. I have no good idea about short codes. Can you please help me to create a shot code?

1

You should read the Shortcode API as suggested. This should give you an overview of what is happening and how shortcodes should be used. One important thing to remember here, shortcode content should be returned, not echo'ed. Here is also a tutorial that help me a lot.

Just a quick tip here, shortcodes should always go into a plugin. If you haven't yet created one, go and read functionality plugin

The correct way of constructing your shortcode would be. Your shortcode will be [my-shortcode] This is untested though

add_shortcode( 'my-shortcode', 'my_custom_query_shortcode' );
function my_custom_query_shortcode( $atts ) {
    ob_start();

$catquery = new WP_Query( 'cat=3&posts_per_page=10' );

 if ( $catquery->have_posts() ) : 
   while($catquery->have_posts()) : $catquery->the_post();
      ?>
      <ul>
        <li><h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>   </h3>

        <ul>
           <li><?php the_content(); ?></li>
        </ul>
        </li>
      </ul>
      <?php 
      endwhile;

     $myvariable = ob_get_clean();

     return $myvariable;

 endif;    

}

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.