简体   繁体   中英

WP Shortcode to display posts by ID

Currently, I have a shortcode that displays a specific set of posts by specifying the post ID inside the function. But I would like to change this so the user can specify the post IDs as shortcode attributes.

Currently

[fsgrid]

Desired:

[fsgrid id="1, 2, 3"]

Here is the current code

public function shortcode_handler($atts) {
    $atts = shortcode_atts(
      array(
        'posts_per_page' => 100 ,
        'orderby' => 'post__in',
        'post__in' => array(1, 2, 3)
      ), $atts, 'fsgrid'
    );

    return $this->grid($atts);
  }

How do I change it? Any help is much appreciated.

explode will be your best option. Firstly extract your shortcode ids attributes then explode the comma separated string to an array.

See: https://codex.wordpress.org/Function_Reference/shortcode_atts

public function shortcode_handler($atts) {
    extract(shortcode_atts(array(
        'id' => null
    ), $atts, 'fsgrid'));    


   $post_ids = explode(",", strval($id));

   $args = array(
        'posts_per_page' => 100 ,
        'orderby' => 'post__in',
        'post__in' => $post_ids
      );

    return $this->grid($args);
  }

Then you call you shortcode [fsgrid id="1,2,3"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM