1

So I'm using custom loop and shortcode to insert it in any page. Like this:

function register_custom_shortcode($atts){

    extract(shortcode_atts(array(
        'ids' => '', // this is what I need
        ), $atts));

    $cutom_loop = new WP_Query( array( 
        'post_type' => 'cutom_post',
        'orderby' => 'menu_order',
        'order' => 'ASC'
        ) );

    ob_start();


    while ( $cutom_loop->have_posts() ) : $cutom_loop->the_post(); ?>

    <article id="post-<?php the_ID(); ?>" <?php post_class(''); ?>>

    // post thumb, title and so on

    </article>

    <?php endwhile;


    wp_reset_postdata();
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}

add_shortcode( 'custom_loop', 'register_custom_shortcode' );

How shoud I handle this ids to have shortcode like this: [custom_loop ids="112,93,34,91"]?

EDIT:

Ok, if i add 'post__in' => array(189,173) to new WP_Query it will output only this two posts, but still can't figure out how to grab this ids from shortcode.

1 Answer 1

3

If you use comma separated id's in the shortcode like "112,93,34,91", you can make use of the explode function to make an array out of the string, like the following:

extract(shortcode_atts(array(
    'ids' => ''
), $atts));

$id_array = explode(',', $ids); 

Then you just have to use 'post__in' => $id_array

1
  • Is there a way to show all IDS if the $atts is not set? Right now I just have the if statement wrapped around the query args but I am wondering if there is a cleaner way to do this? if( isset( $atts['ids'] ) ) { $options = array( 'post_type' => 'webinars', 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'ASC', 'post__in' => $id_array, ); } else {...}
    – tiadotdev
    Commented Mar 3, 2021 at 23:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.