我试图在模板标题中显示一个随机产品。因此,每次有人访问或刷新时,标题中将显示不同的产品。
我搜索并找到了这个
<?php
echo do_shortcode(\'[products ids="1, 2, 3, 4, 5"]\');
?>
但这只显示具有此调用中提到的ID的产品。有没有办法得到一个随机产品?我试图在模板标题中显示一个随机产品。因此,每次有人访问或刷新时,标题中将显示不同的产品。
我搜索并找到了这个
<?php
echo do_shortcode(\'[products ids="1, 2, 3, 4, 5"]\');
?>
但这只显示具有此调用中提到的ID的产品。有没有办法得到一个随机产品?您可以像对待任何其他帖子类型一样对待产品,并使用get_posts()
. 将检索到的帖子数量限制为1,并将orderby参数更改为random:
$args = array(
\'posts_per_page\' => 1,
\'orderby\' => \'rand\',
\'post_type\' => \'product\' );
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata();
您也可以使用新WP_Query()
这将是类似的。Here is a bit of code I am using for mine its for recent products but is doing the job. Just add to page you want to show them on.
[recent_products per_page="4" columns="4" orderby="rand" order="rand"]
有一个Random Products Widget for WooCommerce 您可以将其添加到标题小部件区域。
我创建了自定义帖子类型add_action(\'after_setup_theme\', \'cptui_register_my_cpt_packaged\'); function cptui_register_my_cpt_packaged() { register_post_type(\'packaged\', array( \'label\' => \'Packaged Foods\', \'description\' => \'\', \'pub