How I make a shortcode for this code?

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="https://wordpress.stackexchange.com/questions/154858/<?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;    

}

Leave a Comment