Is it possible not to define category on function.php and add the shortcode [shortcode cat=1] to display the products?

You can use shortcode_atts for get your category which you are pass in [home_slider cat=1]. I assume that your taxonomy is category. you can replace with your taxonomy. You can also pass multiple cat id using comma separated. for eg [home_slider cat=1,2,3]. It will return slider of that category post.

function home_slider($params = array()){
    extract(shortcode_atts(array(
        'cat' => "",
    ), $params));

    ob_start();
     $args = array(
    'post_type'   => 'productslider',
    'order'          => 'DESC',
    'orderby'        => 'date',
    'posts_per_page' => 3,
    'post_status' => array('publish'),
    );
     if(!empty($cat))
     {
        if( strpos($cat, ',' ) !== false ) {
            $cat = explode( ',' , $cat );
        }
       $args['tax_query'] = array(
                array(
                    'taxonomy' => 'category',
                    'field' => 'term_id',
                    'terms' => $cat
                     )
                );
    }
    $hm_sliders = get_posts( $args );?>
    <div class="cp-heroWrapper">
      <div class="slideshow js-slideshow cp_heroSlider">
        <?php
    foreach($hm_sliders as $hm_slider){
    $feat_image = wp_get_attachment_url( get_post_thumbnail_id($hm_slider->ID) );?>
        <div class="slide">
          <div class="slide_img">
            <div class="cp-heroBannerImg">
                <a href="https://wordpress.stackexchange.com/questions/354764/<?php echo get_post_meta($hm_slider->ID,"imageURlLink', true );?>" title=""><img src="<?php echo $feat_image; ?>"><div class="bg_overlay"></div></a>
            </div>

            <div class="cp-heading">
              <h2><a href="https://wordpress.stackexchange.com/questions/354764/<?php echo get_post_meta($hm_slider->ID,"imageURlLink', true );?>" title=""><?php echo $hm_slider->post_title ?></a></h2>
            </div>

          </div>
        </div>
        <?php } ?>
      </div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode( 'home_slider', 'home_slider' );

Leave a Comment