Reputation: 365
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*/
}
Upvotes: 1
Views: 421
Reputation: 1039
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
Upvotes: 1