我正在尝试显示 6 个特色产品及其缩略图、价格和标题。但是我看不到任何东西,但是如果我使用$loop->found_posts
我可以看到有 6 条记录从数据库中取回。我还在wp-config.php
中添加了这些行以查看错误,但我无法在页面上看到任何错误
WP-配置.php
define('WP_DEBUG', true);
if (WP_DEBUG) {
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', true);
@ini_set('display_errors', 0);
}
这是我显示精选帖子的代码
<?php
$args = array (
'post_type'=>'product',
'meta_key'=>'_featured',
'posts_per_page'=>6
);
$loop= new WP_Query($args);
//echo $loop->found_posts;
while($loop->have_posts()): the_post();
echo '
<div class="col-xs-4">
<div class="custom-product">
<img src="'.woocommerce_get_product_thumbnail(300,335).'">
<div class="price-title">
<h2>'.the_title().'</h2>
<h3>'.$product->get_price_html().'</h3>
</div>
</div>
</div>
';
endwhile;
?>
这里有一些建议:
-
您应该使用:
while( $loop->have_posts() ): $loop->the_post();
而不是:
while( $loop->have_posts() ): the_post();
因为否则,您将设置与全局
$wp_query
对象相关的帖子。 -
请注意,
the_title()
不返回该值,而是echo
-ing 它。 -
确保在循环中定义了
$product
。 -
在辅助查询后使用
wp_reset_postdata()
来还原全局$post
变量。 -
您可以使用
WP_Query
的posts
属性:var_dump( $loop->posts );
以窥视查询的帖子数组。
-
要检查生成的 SQL 查询,我们可以使用
WP_Query
的request
属性:echo $loop->request
当我们需要调试查询时,这会派上用场。
这应该按预期工作。 woocommerce_get_product_thumbnail
回显图像标记 HTML,则需要作为参数传递的是现有的缩略图名称以及占位符的宽度和高度。
<?php
$args = array(
'post_type' => 'product',
'meta_key' => '_featured',
'posts_per_page' => 6
);
$loop = new WP_Query( $args );
global $product;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-xs-4">
<div class="custom-product">
<?php echo woocommerce_get_product_thumbnail( 'shop_catalog', 300, 335 ); ?>
<div class="price-title">
<h2><?php the_title(); ?></h2>
<h3><?php echo $product->get_price_html(); ?></h3>
</div>
</div>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
您可以按照此处所述设置自定义图像尺寸 -> 伍商务法典
shop_catalog 我在谷歌上的第一次点击返回了以下链接。
根据他们的说明,我更新了您的代码。以下代码应该有效:
<?php
$args = array (
'post_type' => 'product',
'meta_key' => '_featured',
'meta_value' => 'yes',
'posts_per_page' => 6
);
global $post;
$loop= new WP_Query($args);
//echo $loop->found_posts;
while($loop->have_posts()): $loop->the_post();
$post = $loop->post;
setup_postdata( $post );
$product = get_product( $loop->post->ID );
echo '
<div class="col-xs-4">
<div class="custom-product">
<img src="' . woocommerce_get_product_thumbnail('shop_catalog ', 300,335) . '">
<div class="price-title">
<h2>' . get_the_title(). '</h2>
<h3>' . $product->get_price_html() . '</h3>
</div>
</div>
</div>
';
endwhile;
wp_reset_postdata();
?>
我遇到了同样的问题。试试这个 !为我工作
<?php
$featured_query = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN'
),
),
) );
?>