最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - IF ( ! $loop->have_posts() ) condition doesn't work - WP_Query

programmeradmin3浏览0评论

So I'm almost positive I had this working perfectly, then somewhere out of nowhere it seemed not to. I've tinkered around and have had it hide everything and then hide nothing at all. Wondering if anyone spots something I'm doing wrong?

The code below should basically scan all of my products - simple & variable - to see whether any IN STOCK products have sale prices on them. If there are no IN STOCK products with sale prices, hide a certain CSS ID. Otherwise, do nothing. Not sure what I'm missing...

// -----------------------------------------
// HIDE WEEKLY SPECIALS IF THERE ARE NO PRODUCTS

function weeklyspecials() {
    $args = array(
            'post_type'      => 'product',
            'posts_per_page' => 4,
            'meta_query'     => array(
                    'relation' => 'AND',
                    array(
                        'relation' => 'OR',
                        array( // Simple products type
                            'key'           => '_sale_price',
                            'value'         => 0,
                            'compare'       => '>',
                            'type'          => 'numeric'
                        ),
                        array( // Variable products type
                            'key'           => '_min_variation_sale_price',
                            'value'         => 0,
                            'compare'       => '>',
                            'type'          => 'numeric'
                        )
                    ),
                    array( // Stock status
                        'key' => '_stock_status',
                        'value' => 'instock'
                    )
                )
        );

        $loop = new WP_Query( $args );

        if ( ! $loop->have_posts() ) {
            echo '<style>#weeklyspecials {display:none;}</style>';
        }
}
add_action ( 'wp_body_open', 'weeklyspecials' );

Results of my VAR_DUMP()

object(WP_Query)[18711]
  public 'query' => 
    array (size=3)
      'post_type' => string 'product' (length=7)
      'posts_per_page' => int 4
      'meta_query' => 
        array (size=3)
          'relation' => string 'AND' (length=3)
          0 => 
            array (size=3)
              ...
          1 => 
            array (size=2)
              ...
  public 'query_vars' => 
    array (size=65)
      'post_type' => string 'product' (length=7)
      'posts_per_page' => int 4
      'meta_query' => 
        array (size=3)
          'relation' => string 'AND' (length=3)
          0 => 
            array (size=3)
              ...
          1 => 
            array (size=2)
              ...
      'error' => string '' (length=0)
      'm' => string '' (length=0)
      'p' => int 0
      'post_parent' => string '' (length=0)
      'subpost' => string '' (length=0)
      'subpost_id' => string '' (length=0)
      'attachment' => string '' (length=0)
      'attachment_id' => int 0
      'name' => string '' (length=0)
      'pagename' => string '' (length=0)
      'page_id' => int 0
      'second' => string '' (length=0)
      'minute' => string '' (length=0)
      'hour' => string '' (length=0)
      'day' => int 0
      'monthnum' => int 0
      'year' => int 0
      'w' => int 0
      'category_name' => string '' (length=0)
      'tag' => string '' (length=0)
      'cat' => string '' (length=0)
      'tag_id' => string '' (length=0)
      'author' => string '' (length=0)
      'author_name' => string '' (length=0)
      'feed' => string '' (length=0)
      'tb' => string '' (length=0)
      'paged' => int 0
      'meta_key' => string '' (length=0)
      'meta_value' => string '' (length=0)
      'preview' => string '' (length=0)
      's' => string '' (length=0)
      'sentence' => string '' (length=0)
      'title' => string '' (length=0)
      'fields' => string '' (length=0)
      'menu_order' => string '' (length=0)
      'embed' => string '' (length=0)
      'category__in' => 
        array (size=0)
          empty
      'category__not_in' => 
        array (size=0)
          empty
      'category__and' => 
        array (size=0)
          empty
      'post__in' => 
        array (size=0)
          empty
      'post__not_in' => 
        array (size=0)
          empty
      'post_name__in' => 
        array (size=0)
          empty
      'tag__in' => 
        array (size=0)
          empty
      'tag__not_in' => 
        array (size=0)
          empty
      'tag__and' => 
        array (size=0)
          empty
      'tag_slug__in' => 
        array (size=0)
          empty
      'tag_slug__and' => 
        array (size=0)
          empty
      'post_parent__in' => 
        array (size=0)
          empty
      'post_parent__not_in' => 
        array (size=0)
          empty
      'author__in' => 
        array (size=0)
          empty
      'author__not_in' => 
        array (size=0)
          empty
      'facetwp' => boolean true
      'ignore_sticky_posts' => boolean false
      'suppress_filters' => boolean false
      'cache_results' => boolean true
      'update_post_term_cache' => boolean true
      'lazy_load_term_meta' => boolean true
      'update_post_meta_cache' => boolean true
      'nopaging' => boolean false
      'comments_per_page' => string '50' (length=2)
      'no_found_rows' => boolean false
      'order' => string 'DESC' (length=4)
  public 'tax_query' => 
    object(WP_Tax_Query)[18708]
      public 'queries' => 
        array (size=0)
          empty
      public 'relation' => string 'AND' (length=3)
      protected 'table_aliases' => 
        array (size=0)
          empty
      public 'queried_terms' => 
        array (size=0)
          empty
      public 'primary_table' => string 'wp_posts' (length=8)
      public 'primary_id_column' => string 'ID' (length=2)
  public 'meta_query' => 
    object(WP_Meta_Query)[18709]
      public 'queries' => 
        array (size=3)
          0 => 
            array (size=3)
              ...
          1 => 
            array (size=2)
              ...
          'relation' => string 'AND' (length=3)
      public 'relation' => string 'AND' (length=3)
      public 'meta_table' => string 'wp_postmeta' (length=11)
      public 'meta_id_column' => string 'post_id' (length=7)
      public 'primary_table' => string 'wp_posts' (length=8)
      public 'primary_id_column' => string 'ID' (length=2)
      protected 'table_aliases' => 
        array (size=2)
          0 => string 'wp_postmeta' (length=11)
          1 => string 'mt1' (length=3)
      protected 'clauses' => 
        array (size=3)
          'wp_postmeta' => 
            array (size=7)
              ...
          'wp_postmeta-1' => 
            array (size=7)
              ...
          'mt1' => 
            array (size=6)
              ...
      protected 'has_or_relation' => boolean true
  public 'date_query' => boolean false
  public 'request' => string 'SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1  AND ( 
  ( 
    ( wp_postmeta.meta_key = '_sale_price' AND CAST(wp_postmeta.meta_value AS SIGNED) > '0' ) 
    OR 
    ( wp_postmeta.meta_key = '_min_variation_sale_price' AND CAST(wp_postmeta.meta_value AS SIGNED) > '0' )
  ) 
  AND 
  ( mt1.meta_key = '_stock_status' AND mt1.meta_value = 'instock' )
) AND wp_posts.'... (length=735)
  public 'posts' => 
    array (size=0)
      empty
  public 'post_count' => int 0
  public 'current_post' => int -1
  public 'in_the_loop' => boolean false
  public 'comment_count' => int 0
  public 'current_comment' => int -1
  public 'found_posts' => int 0
  public 'max_num_pages' => int 0
  public 'max_num_comment_pages' => int 0
  public 'is_single' => boolean false
  public 'is_preview' => boolean false
  public 'is_page' => boolean false
  public 'is_archive' => boolean true
  public 'is_date' => boolean false
  public 'is_year' => boolean false
  public 'is_month' => boolean false
  public 'is_day' => boolean false
  public 'is_time' => boolean false
  public 'is_author' => boolean false
  public 'is_category' => boolean false
  public 'is_tag' => boolean false
  public 'is_tax' => boolean false
  public 'is_search' => boolean false
  public 'is_feed' => boolean false
  public 'is_comment_feed' => boolean false
  public 'is_trackback' => boolean false
  public 'is_home' => boolean false
  public 'is_privacy_policy' => boolean false
  public 'is_404' => boolean false
  public 'is_embed' => boolean false
  public 'is_paged' => boolean false
  public 'is_admin' => boolean false
  public 'is_attachment' => boolean false
  public 'is_singular' => boolean false
  public 'is_robots' => boolean false
  public 'is_favicon' => boolean false
  public 'is_posts_page' => boolean false
  public 'is_post_type_archive' => boolean true
  private 'query_vars_hash' => string '1f83b003e69dc81d9f9a9bf0531defa3' (length=32)
  private 'query_vars_changed' => boolean true
  public 'thumbnails_cached' => boolean false
  private 'stopwords' => null
  private 'compat_fields' => 
    array (size=2)
      0 => string 'query_vars_hash' (length=15)
      1 => string 'query_vars_changed' (length=18)
  private 'compat_methods' => 
    array (size=2)
      0 => string 'init_query_flags' (length=16)
      1 => string 'parse_tax_query' (length=15)

So I'm almost positive I had this working perfectly, then somewhere out of nowhere it seemed not to. I've tinkered around and have had it hide everything and then hide nothing at all. Wondering if anyone spots something I'm doing wrong?

The code below should basically scan all of my products - simple & variable - to see whether any IN STOCK products have sale prices on them. If there are no IN STOCK products with sale prices, hide a certain CSS ID. Otherwise, do nothing. Not sure what I'm missing...

// -----------------------------------------
// HIDE WEEKLY SPECIALS IF THERE ARE NO PRODUCTS

function weeklyspecials() {
    $args = array(
            'post_type'      => 'product',
            'posts_per_page' => 4,
            'meta_query'     => array(
                    'relation' => 'AND',
                    array(
                        'relation' => 'OR',
                        array( // Simple products type
                            'key'           => '_sale_price',
                            'value'         => 0,
                            'compare'       => '>',
                            'type'          => 'numeric'
                        ),
                        array( // Variable products type
                            'key'           => '_min_variation_sale_price',
                            'value'         => 0,
                            'compare'       => '>',
                            'type'          => 'numeric'
                        )
                    ),
                    array( // Stock status
                        'key' => '_stock_status',
                        'value' => 'instock'
                    )
                )
        );

        $loop = new WP_Query( $args );

        if ( ! $loop->have_posts() ) {
            echo '<style>#weeklyspecials {display:none;}</style>';
        }
}
add_action ( 'wp_body_open', 'weeklyspecials' );

Results of my VAR_DUMP()

object(WP_Query)[18711]
  public 'query' => 
    array (size=3)
      'post_type' => string 'product' (length=7)
      'posts_per_page' => int 4
      'meta_query' => 
        array (size=3)
          'relation' => string 'AND' (length=3)
          0 => 
            array (size=3)
              ...
          1 => 
            array (size=2)
              ...
  public 'query_vars' => 
    array (size=65)
      'post_type' => string 'product' (length=7)
      'posts_per_page' => int 4
      'meta_query' => 
        array (size=3)
          'relation' => string 'AND' (length=3)
          0 => 
            array (size=3)
              ...
          1 => 
            array (size=2)
              ...
      'error' => string '' (length=0)
      'm' => string '' (length=0)
      'p' => int 0
      'post_parent' => string '' (length=0)
      'subpost' => string '' (length=0)
      'subpost_id' => string '' (length=0)
      'attachment' => string '' (length=0)
      'attachment_id' => int 0
      'name' => string '' (length=0)
      'pagename' => string '' (length=0)
      'page_id' => int 0
      'second' => string '' (length=0)
      'minute' => string '' (length=0)
      'hour' => string '' (length=0)
      'day' => int 0
      'monthnum' => int 0
      'year' => int 0
      'w' => int 0
      'category_name' => string '' (length=0)
      'tag' => string '' (length=0)
      'cat' => string '' (length=0)
      'tag_id' => string '' (length=0)
      'author' => string '' (length=0)
      'author_name' => string '' (length=0)
      'feed' => string '' (length=0)
      'tb' => string '' (length=0)
      'paged' => int 0
      'meta_key' => string '' (length=0)
      'meta_value' => string '' (length=0)
      'preview' => string '' (length=0)
      's' => string '' (length=0)
      'sentence' => string '' (length=0)
      'title' => string '' (length=0)
      'fields' => string '' (length=0)
      'menu_order' => string '' (length=0)
      'embed' => string '' (length=0)
      'category__in' => 
        array (size=0)
          empty
      'category__not_in' => 
        array (size=0)
          empty
      'category__and' => 
        array (size=0)
          empty
      'post__in' => 
        array (size=0)
          empty
      'post__not_in' => 
        array (size=0)
          empty
      'post_name__in' => 
        array (size=0)
          empty
      'tag__in' => 
        array (size=0)
          empty
      'tag__not_in' => 
        array (size=0)
          empty
      'tag__and' => 
        array (size=0)
          empty
      'tag_slug__in' => 
        array (size=0)
          empty
      'tag_slug__and' => 
        array (size=0)
          empty
      'post_parent__in' => 
        array (size=0)
          empty
      'post_parent__not_in' => 
        array (size=0)
          empty
      'author__in' => 
        array (size=0)
          empty
      'author__not_in' => 
        array (size=0)
          empty
      'facetwp' => boolean true
      'ignore_sticky_posts' => boolean false
      'suppress_filters' => boolean false
      'cache_results' => boolean true
      'update_post_term_cache' => boolean true
      'lazy_load_term_meta' => boolean true
      'update_post_meta_cache' => boolean true
      'nopaging' => boolean false
      'comments_per_page' => string '50' (length=2)
      'no_found_rows' => boolean false
      'order' => string 'DESC' (length=4)
  public 'tax_query' => 
    object(WP_Tax_Query)[18708]
      public 'queries' => 
        array (size=0)
          empty
      public 'relation' => string 'AND' (length=3)
      protected 'table_aliases' => 
        array (size=0)
          empty
      public 'queried_terms' => 
        array (size=0)
          empty
      public 'primary_table' => string 'wp_posts' (length=8)
      public 'primary_id_column' => string 'ID' (length=2)
  public 'meta_query' => 
    object(WP_Meta_Query)[18709]
      public 'queries' => 
        array (size=3)
          0 => 
            array (size=3)
              ...
          1 => 
            array (size=2)
              ...
          'relation' => string 'AND' (length=3)
      public 'relation' => string 'AND' (length=3)
      public 'meta_table' => string 'wp_postmeta' (length=11)
      public 'meta_id_column' => string 'post_id' (length=7)
      public 'primary_table' => string 'wp_posts' (length=8)
      public 'primary_id_column' => string 'ID' (length=2)
      protected 'table_aliases' => 
        array (size=2)
          0 => string 'wp_postmeta' (length=11)
          1 => string 'mt1' (length=3)
      protected 'clauses' => 
        array (size=3)
          'wp_postmeta' => 
            array (size=7)
              ...
          'wp_postmeta-1' => 
            array (size=7)
              ...
          'mt1' => 
            array (size=6)
              ...
      protected 'has_or_relation' => boolean true
  public 'date_query' => boolean false
  public 'request' => string 'SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1  AND ( 
  ( 
    ( wp_postmeta.meta_key = '_sale_price' AND CAST(wp_postmeta.meta_value AS SIGNED) > '0' ) 
    OR 
    ( wp_postmeta.meta_key = '_min_variation_sale_price' AND CAST(wp_postmeta.meta_value AS SIGNED) > '0' )
  ) 
  AND 
  ( mt1.meta_key = '_stock_status' AND mt1.meta_value = 'instock' )
) AND wp_posts.'... (length=735)
  public 'posts' => 
    array (size=0)
      empty
  public 'post_count' => int 0
  public 'current_post' => int -1
  public 'in_the_loop' => boolean false
  public 'comment_count' => int 0
  public 'current_comment' => int -1
  public 'found_posts' => int 0
  public 'max_num_pages' => int 0
  public 'max_num_comment_pages' => int 0
  public 'is_single' => boolean false
  public 'is_preview' => boolean false
  public 'is_page' => boolean false
  public 'is_archive' => boolean true
  public 'is_date' => boolean false
  public 'is_year' => boolean false
  public 'is_month' => boolean false
  public 'is_day' => boolean false
  public 'is_time' => boolean false
  public 'is_author' => boolean false
  public 'is_category' => boolean false
  public 'is_tag' => boolean false
  public 'is_tax' => boolean false
  public 'is_search' => boolean false
  public 'is_feed' => boolean false
  public 'is_comment_feed' => boolean false
  public 'is_trackback' => boolean false
  public 'is_home' => boolean false
  public 'is_privacy_policy' => boolean false
  public 'is_404' => boolean false
  public 'is_embed' => boolean false
  public 'is_paged' => boolean false
  public 'is_admin' => boolean false
  public 'is_attachment' => boolean false
  public 'is_singular' => boolean false
  public 'is_robots' => boolean false
  public 'is_favicon' => boolean false
  public 'is_posts_page' => boolean false
  public 'is_post_type_archive' => boolean true
  private 'query_vars_hash' => string '1f83b003e69dc81d9f9a9bf0531defa3' (length=32)
  private 'query_vars_changed' => boolean true
  public 'thumbnails_cached' => boolean false
  private 'stopwords' => null
  private 'compat_fields' => 
    array (size=2)
      0 => string 'query_vars_hash' (length=15)
      1 => string 'query_vars_changed' (length=18)
  private 'compat_methods' => 
    array (size=2)
      0 => string 'init_query_flags' (length=16)
      1 => string 'parse_tax_query' (length=15)
Share Improve this question edited Apr 9, 2020 at 8:11 cybmeta 20.6k5 gold badges47 silver badges57 bronze badges asked Apr 9, 2020 at 7:02 Bruce BannerBruce Banner 32 bronze badges 9
  • 1 did you var_dump the $loop to see what is inside or output expected result? This could make sure the query return what you are looking for first. – 西門 正 Code Guy - JingCodeGuy Commented Apr 9, 2020 at 7:16
  • Yup. I will add that to my question now. I'm not really sure what to make of it though - as I'm a newbie and usually my var_dumps are for true or false, or integers and the like. – Bruce Banner Commented Apr 9, 2020 at 7:23
  • There is no posts found in your query. I suggest you reduce your query arguments to less conditions and start from simple one like only post_type and post_per_page first. Because it could be your condition not working. If you are familiar with phpmyadmin you could use the SQL in the var_dump result to put and see if there is any result. If the result in phpmyadmin is empty then your query is going wrong somewhere. – 西門 正 Code Guy - JingCodeGuy Commented Apr 9, 2020 at 8:19
  • I think you are right, but why? It must have something to do with the variable products - because that is where the sale is. For some reason it isn't recognizing that. – Bruce Banner Commented Apr 9, 2020 at 8:47
  • Form your comment in my answer, you get zero posts but you should get at least 1, right? Could you add more details to the question about what you expect and what you get? You just said "it doesn't work as I expected" but you didn't explain what you expect to get and what actually get. That could make us able to help you better. I thought that your problem is that you correctly get zero posts but have_posts() evaluate to true instead to false, but it seems I didn't get you. Please, explain further your problem. – cybmeta Commented Apr 9, 2020 at 8:52
 |  Show 4 more comments

1 Answer 1

Reset to default 0

Products variations are a stored as a different post type, product_variation, so you have to add that post type to the query:

'post_type' => array( 'product', 'product_variation' )

Also, you could try to use WooCommerce specific functions, like wc_get_product_ids_on_sale(), wc_get_products() and so on, they could make your life easier when coding for WooCommerce.

发布评论

评论列表(0)

  1. 暂无评论