Shortcode and get_template_part

I'm developing my own plugin for my wordpress. I create a shortcode for my plugin and CPT with a custom taxonomy and custom single-CPT.

When I try to use the function get_template_part() in my shortcode, the result is a call to a single.php template from the theme. How I can limit where get_template_part can look for files?

This is my shortcode:

function shortcode_display_products ( $atts ){

 global $wpdb;
 $query = '';

 $atts = shortcode_atts( array(
   'categories' = ''
 ), $atts, 'shortcode_display_products');


if( !empty($atts['categories'])  !is_null($atts['categories']) ){
$query = new WP_Query( array(
  'post_type'     =  'products',
  'post_status'   = 'public',
  'tax_query' = array(
    array(
      'taxonomy'= 'groups',
      'field'   = 'slug',
      'terms'   = '"'.$atts['categories'].'"'
    )
  ),
  'showposts'     =  -1,
  'orderby'       =  'date',
  'order'         =  'DESC'
));
}
else{
$query = new WP_Query( array(
  'post_type'   =  'products',
  'post_status' = 'public',
  'showposts'   =  -1,
  'orderby'     =  'date',
  'order'       =  'DESC'
));
}
ob_start();

if( $query-have_posts() ){

  $c = 0;

  while ( $query - have_posts() ){

      $query - the_post();
      get_template_part('single','products');

    $c++;
 }
}
else{
 return esc_html__('Not found any product register',P_TEXTDOMAIN);
}

wp_reset_postdata();

return ob_get_clean();

}

add_shortcode('display_products','shortcode_display_products');

This is my single-products:

if ( !is_single() ){

 include '/form/products-form.php';
 $idnumber = ( is_single() )? '': '-'.$c;
?

div class="card"
  div class="card-header" id="heading?= $idnumber?"
    h5 class="mb-0"
      button class="btn btn-link" data-toggle="collapse" data-target="#collapse?= $idnumber?" aria-expanded="true" aria-controls="collapse?= $idnumber?"
        ?= $post-title ?
      /button
    /h5
  /div
  div id="collapse?= $idnumber?" class="collapse show" aria-labelledby="heading?= $idnumber?" data-parent="#accordion"
    div class="card-body"
      ?= $post-content ?
      ?php create_product_form() ?
    /div
  /div
/div

?php }
else{ _e('nothing else',P_TEXTDOMAIN);}

}

Topic single get-template-part shortcode plugin-development custom-post-types Wordpress

Category Web


Function get_template_part() load file only from theme directory (or child theme). There is no filter or action hook that would change this behavior.

You will need to write your own get_template_part() variant to load files from the plugin directory (replace the locate_template() call from the original function). Or write an explicit:

$query->the_post();
include plugin_dir_path( __FILE__ ) . 'single-products.php';

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.