1
votes

In my shortcode I want to get posts from my custom_type_post but filtering them with ids, post_type and posts_per_page

e.g. [myshortcode type="my_custom_type_post"] - to show all posts in my_custom_type_post

or [myshortcode type="my_custom_type_post" no_of_posts="3"] - to show only 3 posts

or [myshortcode type="my_custom_type_post" no_of_posts="1" id="112"] - to show that specific post

Here is my code. It works when I only send type and posts_per_page and ids BUT doesn't work when I want to display all posts or with no_of_posts

// extracting values from shortcode
       extract( shortcode_atts( array (
        'type' => '',
        'no_of_posts' => '',
        'id' => ''
    ), $atts ) );

   $id_array = array_map('intval',explode(',',$id));

$args = array(
    'post_type' => $type,
    'posts_per_page' => $no_of_posts,
    'post__in' => $id_array
);

and then passing the values to wp_query

$query = new WP_Query( $args );
if( $query->have_posts() ){

/*printing out results*/

}
1
Just use 'post__in' => $id_array because already you passed array to valueJaydp
still doesn't work when I want to display all posts or with no_of_postsMelbDev
check my answerJaydp

1 Answers

1
votes

You must have to use conditional code as below

extract( shortcode_atts( array (
        'type' => '',
        'no_of_posts' => '',
        'id' => ''
    ), $atts ) );

$args['post_type'] = $type;

if($no_of_posts) {
    $args['posts_per_page'] = $no_of_posts;
} else {
    $args['posts_per_page'] = '-1';
}

if($id) {
    $args['post__in'] = array_map('intval',explode(',',$id));
}

I'd just setup arguments based on condition