How to make wordpress shortcode

2019-09-06 12:00发布

问题:

I have this code to show all post of category and thumbnail for 1st post of them.

<?php $recent = new WP_Query(); ?>
<?php $recent->query( 'cat=1&showposts=5' ); ?>
<?php $is_first_post = true; ?>
<?php while( $recent->have_posts() ) : $recent->the_post(); ?>
    <ul>
      <li>
      <?php 
      if ( $is_first_post  && has_post_thumbnail() ) {
        the_post_thumbnail(); 
        $is_first_post = false; 
        }
        ?>
        <a href="<?php the_permalink(); ?>">
        <?php the_title(); ?>
        </a>
      </li>
    </ul>
<?php endwhile; ?>

but i want show this using shortcode.which using category & post number but i can not make shortcode

回答1:

A shortcode is a PHP function. You need a function that accepts all your arguments. For example-

function get_posts($atts) {
  extract( shortcode_atts( array(
    'cat_id' => 'cat_id',
    'num_posts' => 'num_posts'
  ), $atts ) );

  $loop = array(
    'cat' => $cat_id,
    'posts_per_page' => $num_posts
  );

  if ( $loop->have_posts() ) :
    while ( $loop->have_posts() ) : $loop->the_post();
      // YOUR CODE HERE
    endwhile;
  endif;
}

add_shortcode( 'getposts', 'get_posts' );

Your Shortcode will look like this-

getposts[cat_id="1", num_posts="5"]

This code have not been tested but this is pretty much how you do it



回答2:

First of all you just change your function name.

In wordpress get_posts() is one function so you did not create your custom function same name.

https://developer.wordpress.org/reference/functions/get_posts/



回答3:

Add this code in function.php and this is your shortcode "[my_form_shortcode cat="1" showposts="5"]".

function my_form_shortcode($atts) {
 ob_start();
 $atts = shortcode_atts(
 array(
        'cat' => '1',
        'showposts' => '5',
 ), $atts, 'my_form_shortcode' );

//YOUR CODE START

 $recent = new WP_Query(); 
 $query = "cat=".$atts['cat']."&showposts=".$atts['showposts'];
 $recent->query( $query ); 
 $is_first_post = true; 
 while( $recent->have_posts() ) : $recent->the_post(); ?>
<ul>
  <li>
  <?php 
   if ( $is_first_post  && has_post_thumbnail() ) {
    the_post_thumbnail(); 
    $is_first_post = false; 
   }
  ?>
  <a href="<?php the_permalink(); ?>">
  <?php the_title(); ?>
  </a>
 </li>
 </ul>
 <?php endwhile; 
 //YOUR CODE END

 return ob_get_clean(); 
 }

add_shortcode( 'my_form_shortcode', 'my_form_shortcode' );


回答4:

function ShowProduct()
{
  $data = "Welcome to wordpress shortcode.";
  return $data;
}

add_shortcode('products', 'ShowProduct');

http://www.codexwp.com/issues/how-to-create-shortcode-in-wordpress/