• I have created a shortcode with a custom query and I’m using it on many pages.

    Basically, I’m displaying products by the current category and now I added some functionality about sorting the products by price ASC and DESC. My problem is when I’m selecting a sorting option some products without price don’t get displayed and some other products without price get displayed.

    My issue is that I want the products without price to get displayed normally. I have already tried to re-save the permalinks and also re-save the products that don’t get displayed.

    Also, I did a test in one of the products that don’t get displayed. I inserted a price and save, then delete the price and save it again. After that, the product is displaying as it supposed to but I can’t do that on every product that doesn’t get displayed, especially on the production site.

    I’m working on the localhost so I don’t have a link to share, but I can share a part of my code.

     if(  $_SESSION['MyOrder'] == 'menu_order' ) {
    
           $args = array(
                'paged' => $paged,
                'post_parent' => $parent,
                'post_type' => $TheTypes,
                'posts_per_page' => $perpage,
                'sort_column'   => 'menu_order',
                'orderby' => 'menu_order',
                'post_status' => 'publish',           
                'tax_query' => array(
                              array(
                              'taxonomy' => 'product_cat',
                              'field' => 'slug',
                              'terms' => $CategoriesToDisplay,
                            ),
                ) 
            );
           
          }else{ 
            $args = array(
                'paged' => $paged,
                'post_parent' => $parent,
                'post_type' => $TheTypes,
                'posts_per_page' => $perpage,
                'meta_key' => '_price',
                'orderby' => 'meta_value_num', 
                'order' => $_SESSION['MyOrder'],
                'post_status' => 'publish',       
                'tax_query' => array(
                              array(
                              'taxonomy' => 'product_cat',
                              'field' => 'slug',
                              'terms' => $CategoriesToDisplay,                    
                            ), 
                ) 
            );           
           
           }
    
        $CustomQuery = new  WP_Query( $args );
    
    

    Is there something that I can add to my arguments so the products with no price get displayed?

    thank you in advance.

Viewing 10 replies - 1 through 10 (of 10 total)
  • Hi

    Why you passed 'meta_key' => '_price' as argument when you need to show no price products?

    You created a condition on price, remove it and try to test your code.

    Good luck

    Thread Starter olgamm

    (@olgamm)

    Hi @yazdaniwp,

    because I want to sort the products by the price. And I thought that if a product has no price then it will be equal to zero or something

    • This reply was modified 6 years, 2 months ago by olgamm.
    • This reply was modified 6 years, 2 months ago by olgamm.

    OK

    Try this plese:

    $args = array(
        'paged' => $paged,
        'post_parent' => $parent,
        'post_type' => $TheTypes,
        'posts_per_page' => $perpage,
        'order' => $_SESSION['MyOrder'],
        'post_status' => 'publish',
        'meta_query'  => array(
             array(
                'key'     => '_price',
                'compare' => 'EXISTS',
             )
         ),    
        'tax_query' => array(
             array(
                 'taxonomy' => 'product_cat',
                 'field' => 'slug',
                 'terms' => $CategoriesToDisplay,                    
             ), 
        ),
        'orderby'     => array( '_price' => 'DESC' ),
    );
    Thread Starter olgamm

    (@olgamm)

    @yazdaniwp

    tried it. The code doesn’t sort the products. :/

    Thread Starter olgamm

    (@olgamm)

    @yazdaniwp

    I need to ask you about the code. Why at the last row do you set the orderby DESC?
    The values DESC and ASC are in the $_SESSION[‘MyOrder’].

    $args = array(
        'paged' => $paged,
        'post_parent' => $parent,
        'post_type' => $TheTypes,
        'posts_per_page' => $perpage,
        'post_status' => 'publish',
        'meta_query'  => array(
             array(
                'key'     => '_price',
                'compare' => 'EXISTS',
             )
         ),    
        'tax_query' => array(
             array(
                 'taxonomy' => 'product_cat',
                 'field' => 'slug',
                 'terms' => $CategoriesToDisplay,                    
             ), 
        ),
        'orderby'     => array( '_price' => $_SESSION['MyOrder'] ),
    );
    Thread Starter olgamm

    (@olgamm)

    @yazdaniwp, yes I tried this already :/ but nothing changed.

    OK

    If you can, submit all of your shortcode’s code for a closer look.

    Thanks

    Thread Starter olgamm

    (@olgamm)

    Below is the code

    <?php 
    global $wp;
    
    global $paged;
    global $MyBase;
    global $MyPost;
    
    function MyProducts($atts) {
      
        //extract arguments from the shortcode 
        extract( shortcode_atts( array(
            'type' => '' ,
            'perpage' => 5,
            'category' => '',
            'order' => '',
        ), $atts ) );
    
          $TheTypes = explode(',', $type);
    
        if( isset( $atts['category'] ) ) {           
            $CategoriesToDisplay = explode(',', $category);
        }
          
        $output = '<div class="TheStartOfmyData"> <div class="clear">  </div> ';
    
       //Pagination
       $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
         
        // get actual Url
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://".$_SERVER['HTTP_HOST']."".$_SERVER['REQUEST_URI']; 
    
        // Reset Session args
        if ($_SESSION['MyCategory'] !== $atts['category']) {
          $_SESSION['MyOrder'] = "menu_order";
          $_SESSION['MyCategory'] = $atts['category'];
          $_SESSION['MyBase'] =  $actual_link;
    
       }
    
        $output .= '
        <div class="cont" style="text-align:right;">
    
        <input type="hidden"  id="preSelectOption" value='.$_SESSION['MyOrder'].' >
        <input type="hidden"  id="SessionCat" value='.$_SESSION['MyCategory'].' >
     
    
          <div class="form-group" style="width:30%;display:inline-grid;">
            <label for="sel1">Order By:</label>
            <select class="form-control" id="sel1" >
              <option value=" "> </option>
              <option value="menu_order">None</option>
              <option value="ASC">Asc</option>
              <option value="DESC">Desc</option>
            </select>
            <input type="hidden"  id="categories" value='. $category.' > 
     
          </div>
        </div>
        <script>
    jQuery(document).ready(function($)
    {
      var CurrentCat = document.getElementById("categories").value;
      var SessionCat = document.getElementById("SessionCat").value;
    
      var PreSelectOption = document.getElementById("preSelectOption").value;
       Array.from(document.querySelector("#sel1").options).forEach(function(option_element) {
          if(option_element.value === PreSelectOption ){
             option_element.setAttribute("selected", true);
          }
       });
    
           
          $.ajax({
             type: "POST",   
             url: ajaxurl_try.ajaxurl,
             data: {
                 "action": "RedoTheShortcode",            
                 "order" : "'.$_SESSION["MyOrder"].'" ,
                 "category" : CurrentCat,
                 "MyBase" :  "'.$_SESSION["MyBase"].'" 
                  
             },
             success: function(data) {
                   console.log(data);                          
               },
             error: function(errorThrown){
                 console.log(errorThrown);
              }
           });  
      
    
       $("#sel1").change( function(){
        
          var order = document.getElementById("sel1").value;
          var category = document.getElementById("categories").value;
          var MyBase = window.location.href;
          $.ajax({
             type: "POST",   
             url: ajaxurl_try.ajaxurl,
             data: {
                 "action": "RedoTheShortcode",
                 "order" : order,
                 "category" : category,
                 "MyBase" : MyBase
             },
             success: function(data) {
                   console.log(data);                          
                   // $(".MyCustomProds").html(data); 
                   window.location.replace("' .$_SESSION['MyBase'] .'");
    
               },
             error: function(errorThrown){
                 console.log(errorThrown);
              }
           });  
       }); 
    });
        </script>';
    
     
        // Display for Debug purposes 
        $output.='<h2> ORDER='.  $_SESSION['MyOrder'] .'</h2>';
        $output.='<h2> SessionCat='.  $_SESSION['MyCategory'] .'</h2>';
        $output.='<h2> CAT='. $category .'</h2>';
    
        // Default menu order else sort by asc or desc
        if(  $_SESSION['MyOrder'] == 'menu_order' ) {
    
           $args = array(
                'paged' => $paged,
                'post_parent' => $parent,
                'post_type' => $TheTypes,
                'posts_per_page' => $perpage,
                'sort_column'   => 'menu_order',
                'orderby' => 'menu_order',
                'post_status' => 'publish',           
                'tax_query' => array(
                              array(
                              'taxonomy' => 'product_cat',
                              'field' => 'slug',
                              'terms' => $CategoriesToDisplay,
                            ),
                ) 
            );
           
          }else{ 
            $args = array(
                    'paged' => $paged,
                    'post_parent' => $parent,
                    'post_type' => $TheTypes,
                    'posts_per_page' => $perpage,
                    'meta_key' => '_price',
                    'orderby' => 'meta_value_num', 
                    'order' => $_SESSION['MyOrder'],
                    'post_status' => 'publish',       
                    'tax_query' => array(
                                  array(
                                  'taxonomy' => 'product_cat',
                                  'field' => 'slug',
                                  'terms' => $CategoriesToDisplay,                    
                                ), 
                    ) 
                );   
           }
    
        //Begin the loop
        $CustomQuery = new  WP_Query( $args );
     
        while ( $CustomQuery->have_posts() ) : $CustomQuery->the_post();
    
            $product='';
            $Basket='';
            $on_cat='';
          //Chech if the product has price then add currency symbol
          if (get_post_meta( get_the_ID(), '_regular_price', true)){
          
           if(strpos($_SERVER['REQUEST_URI'], '/en/') !== false){ 
              $WithoutVat_Message = '<span class="VATMsg"> without VAT </span>';
              $WithVat_Message = '<span class="VATMsg">VAT incl.</span>';
            }else{            
              $WithoutVat_Message = '<span class="VATMsg" >χωρίς Φ.Π.Α. </span>';
              $WithVat_Message = '<span class="VATMsg">με Φ.Π.Α.</span>';
             
            }
    
            // Basket icon with link to add to cart 
            $product = wc_get_product($CustomQuery->post->ID);
            $Basket = sprintf( '<a href="%s" data-quantity="1" class="%s AddToCartIcon" %s> <div class="QuickAddToCart"> 
                      <img src=" '.get_stylesheet_directory_uri().'/assets/images/shopping_cart.svg" alt="Shopping Cart">
                         </div></a>',
                        esc_url( $product->add_to_cart_url() ),
                        esc_attr( implode( ' ', array_filter( array(
                             'product_type_' . $product->get_type(),
                            $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
                            $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
                        ) ) ) ),
                        wc_implode_html_attributes( array(
                            'data-product_id'  => $product->get_id(),
                            'data-product_sku' => $product->get_sku(),
                            'aria-label'       => $product->add_to_cart_description(),
                            'rel'              => 'nofollow',
                        ) )
                        
                    );
          } else{
            $WithoutVat_Message='';
            $WithVat_Message = '';
          }
          // Display Categories
          $terms = get_the_terms($CustomQuery->post->ID, 'product_cat' );
          if ( $terms && ! is_wp_error( $terms ) ) {
            // only displayed if the product has at least one category
                $cat_links = array();
            if(strpos($_SERVER['REQUEST_URI'], 'en') !== false){
           foreach ( $terms as $term ) {
                  $cat_links[] = '<a href="'.esc_url( site_url() ).'/en/product-category/'.$term->slug.'">'.$term->name.'</a>';
                }
        }else{
           foreach ( $terms as $term ) {
                  $cat_links[] = '<a href="'.esc_url( site_url() ).'/product-category/'.$term->slug.'">'.$term->name.'</a>';
              }
        }
            $on_cat = join( ", ", $cat_links );
          }
               
            $output .= '<div id="container" class="MainContainer container">
                        <div class="row pb-5 MyRow">';
              $output .= '<div class=" col-12 col-sm-3  imageCol " >';
              if ( has_post_thumbnail() ) {
                  $thumnail_URL = wp_get_attachment_url( get_post_thumbnail_id($CustomQuery->ID) );
                  $output .= '<div class="MyImage imageWrapper">
                                <a style="text-decoration:none;" href="'.get_permalink().'">
                                  <div class="bgImage" style="
                                          background: url('. $thumnail_URL.');
                                          height:100%;
                                          background-position: center;
                                          background-size: contain;
                                          background-repeat: no-repeat;">
                                  </div> 
                                </a>
                              </div>';
              }
              $output .= '</div>';
              $output .= '<div class="col-12 col-sm-9 ContentCol"><!--  Start here -->
                          <div class="contentWrapper">';
                 $output .= ' <a style="text-decoration:none;" href="'.get_permalink().'">
                              <h2 class="c_title" style="margin-bottom:5px">'.
                                  get_the_title().
                              '</h2> </a>
                              <div class="ProdCategories" style="padding-bottom:10px;" >
                                '.$on_cat.'
                              </div>';
                
                
                $_product_ = wc_get_product($CustomQuery->post->ID);
                $ThePrice = get_post_meta( get_the_ID(), '_regular_price', true); 
    
               
                if($_product_->is_type( 'variable' ) ){
                  if(strpos($_SERVER['REQUEST_URI'], '/en/') !== false){ 
                    $WithoutVat_Msg = '<span class="VATMsg"> without VAT </span>';
                    $WithVat_Msg = '<span class="VATMsg">Vat Inc.</span>';
                    $FromPrice='<span class="VATMsg" > from </span>';
                    $ToPrice = '<span class="VATMsg" > up to </span>';
                  }else{            
                    $WithoutVat_Msg = '<span class="VATMsg" >χωρίς Φ.Π.Α. </span>';
                    $WithVat_Msg = '<span class="VATMsg">με Φ.Π.Α.</span>';
                    $FromPrice='<span class="VATMsg" > από </span>';
                    $ToPrice = '<span class="VATMsg" > έως </span>';
                  }
    
                  $output .= '<div class="row theMainCon" > <div class="ProdPrices col-12 col-sm-4">';
                  $output .= ' <div class="StyleThePrice">  <div class="RegularPrice">';
                          $available_variations = $_product_->get_available_variations();
                          $min_price = $_product_->get_variation_price( 'min' );
                          $max_price = $_product_->get_variation_price( 'max' );
                          $output .= ''.$FromPrice.' '. $min_price.'€';
                          $output .=$ToPrice .' '. $max_price.'€ '.$WithoutVat_Msg;
    
                  $output .= '</div></div>';
                  $output .= '</div>';
                }else{
                       if (get_post_meta( get_the_ID(), '_sale_price', true)){
                          $output .= '<div class="row theMainCon">
                                      <div class="ProdPrices col-12 col-sm-4">
                                        <div class="StyleThePrice">
                                         <div class="SalePrice">
                                               <del>'.wc_price(get_post_meta( get_the_ID(), '_regular_price', true)).'</del>
                                             </div>
                                             <div class="RegularPrice">'.
                                             wc_price(get_post_meta( get_the_ID(), '_sale_price', true)).' '.$WithoutVat_Message;
                                            $output .='<div class="Price_WithVat"><span>'.wc_price($product->get_price_including_tax(1, $product->get_sale_price())).' </span>'.$WithVat_Message
                                           .'</div></div>
                                      </div>
                                      </div>';
                  }elseif( $ThePrice > 0){
                  
                  
                    	$output .= '<div class="row theMainCon" > <div class="ProdPrices col-12 col-sm-4">';
                             $output .= ' <div class="StyleThePrice">  <div class="RegularPrice">'; 
                                   $output .=wc_price(get_post_meta( get_the_ID(), '_regular_price', true)).' '. $WithoutVat_Message;
                                   $output .='<div class="Price_WithVat"><span>'.wc_price($product->get_price_including_tax(1, $product->get_sale_price())).'</span> '.$WithVat_Message .'</div>';
                              $output .= '</div></div>';
                      	$output .= '</div>';
                    
     
    
                    }else{
    
                          // Check Current product if it has the free software category     
                          $terms = get_the_terms( $product->ID, 'product_cat' );
                          foreach ($terms  as $term  ) {
                              $product_cat_name[] = $term->name;
                              
                          }
    
                          if(strpos($_SERVER['REQUEST_URI'], '/en/') !== false){ 
                              $ContactUsMessage = 'Contact us'; 
                              $FreeSoftCat = 'free software';
                              $FreeProductMessage = 'Free'; 
                            }else{            
                              $ContactUsMessage = 'Κατόπιν <br> επικοινωνίας'; 
                              $FreeSoftCat = 'Δωρεάν Λογισμικά'; 
                              $FreeProductMessage = 'Δωρεάν';
                            }
                         $output .= '<div class="row theMainCon" > <div class="ProdPrices col-12 col-sm-4">';
                                $output .= ' <div class="StyleThePrice MessageAboutPriceStyle" > '; 
                                  $output .= '<span class="MessageAboutPrice"> ';
                                                 //No Price Case
                                              if ( in_array( $FreeSoftCat, $product_cat_name ) ) { 
                                                  $output .= $FreeProductMessage.' </span>';
                                              }else{  
                                                $output .= $ContactUsMessage.' </span>';
                                              }
                                               
                                $output .= '</div>';
                          $output .= '</div>';
                          unset($product_cat_name);
                    }
                } 
                      
    
              $output .= '<div class="ProductDesc col-12 col-sm-8">
                 <div style="display: table-cell; vertical-align: middle;">'.
                                wp_trim_words( get_the_excerpt(),25).
                              '</div></div>
                              </div>
                              <div class="row rowOfButtons">
                                <div class="col-4 ">
                                 <div class="LeftButtonAddToCart">'.$Basket.'</div>
                                </div>
                                <div class="ReadMoreLink col-8">
                                  <div class="TheDots">
                                  <a class="c_hyperlink btn" href="'.get_permalink().'"> <img src=" '.get_stylesheet_directory_uri().'/assets/images/more_dots.svg" alt="Read More"   ></a>
                                  </div>
                                </div>
                              </div>
                         </div>
                         </div><!--  ends here -->';
    
              $output .= '</div> </div>';
    
     
        endwhile;
         wp_reset_query();
    
        
        if(strpos($_SERVER['REQUEST_URI'], '/en/') !== false){
          $Next = 'Next »';
          $Prev = '« Previous';
        }else{
          $Next = 'Επόμενη »';
          $Prev = '« Προηγούμενη';
        }
       
        $output .= '</div>';
        $output .= '</div>';//TheStartOfmyData
    
            // Get the pagination link
            $output .= '<div class="MyPagination">'.
                        paginate_links(array(
                          'base' =>  $_SESSION['MyBase'].'%_%' ,
                          'format' => '?paged=%#%',
                          'total' => $CustomQuery->max_num_pages,
                          // 'current' =>  max( 1, $paged ),
                          'current' =>  $paged ,
                          'prev_next' => True,
                          'prev_text' => __('<span class="pr-2 pl-2 PagLink" style="border:1px solid #fee155;">'.$Prev.'</span>'),
                          'next_text' => __('<span class="pr-2 pl-2 PagLink" style="border:1px solid #fee155;"> '.$Next.' </span>'),
                          'before_page_number' => '<span class="PagLink" style="border:1px solid #fee155;">',
                          'after_page_number'  => '</span>',
                          'type'            => 'plain',
                           'add_args'        => false,
                           'add_fragment'    => ''
                         )).
                    '</div>';
      // For debug purpose 
      $output.='<h2> Numer Of Posts='.$CustomQuery->found_posts .'</h2>';
      $output.='<h2> Pagination ='.$CustomQuery->found_posts/ $perpage .'</h2>';
      $output.='<h2> max_num_pages ='.$CustomQuery->max_num_pages .'</h2>';
    
      // wp_reset_query();
      return $output;  
    }
    ?>
    

    Also in my functions.php I have a function that is called on ajax call

    function RedoTheShortcode()
    {
      if (isset($_POST['order'])){
        $order =$_POST['order'];
      }
      else{
        $order =' ';
      }
      if (isset($_POST['category'])){
        $category =$_POST['category'];
      }
      else{
        $category =' ';
      }
    
      echo do_shortcode("[MyCustomProducts type='product' category=".$category."  order=".$order."  ]");
      die();
    }

    Thank you. I’m from Iran and it’s late now. Check back tomorrow

Viewing 10 replies - 1 through 10 (of 10 total)

The topic ‘Custom Query and sorting issue’ is closed to new replies.