我设法为我的问题找到了一个可行的解决方案.只是不可能通过单独的循环列出产品而不会造成混乱的分页.因此,合乎逻辑的步骤是使用循环并基本上根据图像是否存在来对产品进行排序.这会产生新问题,因为Wordpress排序无法确定图像链接是否指向文件.
但是,您可以在woocommerce中为产品设置“菜单顺序”.然后,如果您在“Woocommerce – >设置 – >目录”下将“默认产品排序”设置为“默认排序”,它将使用此菜单顺序在目录视图中订购产品.
大!但我仍然有17000个产品,我需要为每个产品指定一个菜单.我无法使用原本的woocommerce工具来完成这项工作.所以我决定写一个小插件来根据图像是否存在来更改每个产品的“菜单顺序”.
这是用于写入post数据库的函数:
/**
* This function sets the value of the menu_order of a product to 0 if the product contains an image and 1 if it does not
* @param {int} $offset this is the start number for the batch
* @param {int} $batch The number of products to process in the batch
*/
function setProductMenuOrder($offset, $batch) {
global $post;
$number_completed = 0;
//define the arguments to be used in the loop
$args = array( 'post_type' => 'product','offset' => $offset, 'numberposts' => $batch );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID)); //getting image source
//define post to be updated
$my_post = array();
$my_post['ID'] = $post->ID;
if (@getimagesize($src[0])) { //if image source points to actual image menu order is set to 0
$my_post['menu_order'] = '0';
wp_update_post( $my_post ); //Update the post into the database
$number_completed+=1;
} else { //if it doesn't menu order is set to 1
$my_post['menu_order'] = '1';
wp_update_post( $my_post ); //Update the post into the database
$number_completed+=1;
}
endforeach;
echo '
Number of products edited: '.$number_completed.'.
';}
因为我有这么多产品,我的插件会以较小的批次处理它们.我一次管理着大约2000件产品,没有失败.我确实需要在config.php中调整我的php内存限制
define('WP_MAX_MEMORY_LIMIT', '256M');
我仍然想知道是否有更简单的方法来实现这一点,但目前这种解决方案就足够了.