Search code examples
phpwordpresswordpress-themingshortcodewordpress-shortcode

How do I pass the product category name from the wordpress URL to my shortcode?


I am trying to populate a product dropdown list based on the name of the product category in the URL.

I can do it statically by just entering the name to my function but I would love to do this programmatically so I can get the dropdown list populated based on what product category page the user is in.

My code

function dropdownproducts()
{

  $term_names = array('fruits');
  $query = new WP_Query(array(
    'posts_per_page' => -1,
    'post_type' => 'product',
    'post_status' => 'publish',
    'hide_empty' => 0,
    'orderby' => 'title',
    'tax_query' => array(array(
      'taxonomy' => 'product_cat',
      'field'    => 'name',
      'terms'    => $term_names,
    )),
    'echo' => '0'
  ));

  $output = '<select  onChange="window.location.href=this.value">';
  // foreach ( $products as $product ) {
  if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();

      $permalink = get_permalink($query->post->ID);
      $title = $query->post->post_title;
      $output .= '<option value="' . $permalink . '">' . $title . '</option>';

    endwhile;

    wp_reset_postdata();

    $output .= '</select>';

  else :

    $output = '<p>No products found<p>';

  endif;

  return $output;
}

add_shortcode('products_dropdown', 'dropdownproducts');

According to the code if I just enter the product category name in term names, I get the products under that category. I would love to do that dynamically based on what is at the end of the URL for example if URL is /product-category/food/ I would like to get all products under food in the dropdown.


Solution

  • You can use get_queried_object. check the below code.

    $term = get_queried_object();
    
    if( !empty( $term ) ){
        $term_names = array( $term->name );
    }else{
        $term_names = array( 'fruits' );
    }
    
    $query = new WP_Query( array(
        'posts_per_page' => -1,
        'post_type' => 'product',
        'post_status' => 'publish',
        'hide_empty' => 0,
        'orderby' => 'title',
        'tax_query' => array( array(
            'taxonomy' => 'product_cat', 
            'field'    => 'name',        
            'terms'    => $term_names,
        ) ),
        'echo' => '0'
    ) );