如何根据库存对 WordPress 网站产品进行排序

编程


hi
I have a WooCommerce store website. I use this code to sort products based on inventory. But the code has an error. It dosent work corretct.please guide me. How to sort WordPress site products based on inventory?

我尝试过的:

add_action('init', function() {
	if( isset($_GET['update_products_arv']) ) {
		$products = wc_get_products( [ 'limit' => 500,'offset' => 200] );
		foreach( $products as $product ){
			$total_stock = $product->get_stock_quantity() ? : 0;
			if( $product->is_type( 'variable' ) ){
				$variations = $product->get_children();
				if( !$variations ) continue;
				foreach ($variations as $variation_id) {
					$variation = wc_get_product( $variation_id );
					$total_stock += $variation->get_stock_quantity() ? : 0;
				}
			}
			update_post_meta($product->get_id(), 'xx_stock', $total_stock);
		}
	}
});

add_action('woocommerce_product_query', function($q) {
	if( ! is_admin() ) {
		$q->set('orderby', 'meta_value_num');
		$q->set('meta_key', 'xx_stock');
		$q->set('order', 'DESC');
	}
});

解决方案1

我们无法帮助您:我们无法访问您的库存数据,不知道错误消息(如果有)是什么,也不知道您期望或得到什么。

所以,这将取决于你。
幸运的是,您有一个可用的工具可以帮助您了解正在发生的情况:调试器。 从这里开始: php 调试器 – Google 搜索[^] 然后选择一个看起来适合你的。

在函数的第一行放置一个断点,然后通过调试器运行代码。 然后查看您的代码和数据并找出应该手动发生的情况。 然后单步执行每一行,检查您期望发生的情况是否确实发生。 如果不是,那就是你遇到了问题,你可以回溯(或再次运行它并更仔细地查看)以找出原因。

抱歉,我们无法为您做到这一点 – 您是时候学习一项新的(并且非常非常有用)技能了:调试!

コメント

タイトルとURLをコピーしました