【问题标题】:wordpress get products by meta data and meta valuewordpress 通过元数据和元值获取产品
【发布时间】:2018-04-13 12:14:17
【问题描述】:

我正在尝试按元值和元键显示产品。我正在使用下面的代码来验证 meta_key 和 meta_value。现在,如果没有值为“yes_feat”的元键,则不会打印任何产品。太棒了!

问题是,如果只有 1 个产品的 meta_keys 值为“yes_feat”,则所有其他产品也会打印。我怎样才能做到只有带有元值“yes_feat”的产品显示

        $params = array(

            'post_type' => 'product',  
            'meta_key' => '_featured',  
            'meta_value' => 'yes_feat',  
            'posts_per_page' => 5 

        );
        $wc_query = new WP_Query($params);
        global $post, $product;

        if ($wc_query->have_posts()) { 
            // i am only trying to print products with meta_value = yes_feat
            // but if the statement above is true it prints all products
             echo "print products that have meta_value = yes_feat";
        }   
        else 
        {
            echo "nothing found";
        }

非常感谢

【问题讨论】:

  • 您的代码似乎没问题。如果那里没有附加因素,它不能提供所有产品。使用此代码在 have_posts 循环中打印您的最终查询并将结果粘贴到此处。 $i=0; if ($wc_query->have_posts()) { $i++; if ($i==1) var_dump($wc_query->query); }

标签: php wordpress woocommerce wordpress-theming hook-woocommerce


【解决方案1】:

在 WP_Query 参数中添加元查询

<?php
$params = array(
    'post_type' => 'product',
    'meta_query' => array(
        array('key' => '_featured', //meta key name here
              'value' => 'yes_feat', 
              'compare' => '=',
        )
    ),  
    'posts_per_page' => 5 

);
$wc_query = new WP_Query($params);
global $post, $product;

if( $wc_query->have_posts() ) {

  while( $wc_query->have_posts() ) {

    $wc_query->the_post();

        $wc_query->post_name;
        echo "print products that have meta_value = yes_feat";
        $yes_feat = get_post_meta($wc_query->ID, '_featured',true );
  } // end while

} // end if
 else 
{
    echo "nothing found";
}

wp_reset_postdata();
?>

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2023-03-04
    • 1970-01-01
    • 2021-05-10
    • 2016-05-11
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多