2013-03-01 107 views
5

我有一个运行wordpress插件WooCommerce的wordpress网站。由于本网站正在处理的产品数量庞大,我们一直在网站外部管理产品列表并上传。很多产品还没有图像,但他们有一个硬编码的图像网址,所以我们可以添加它们,当我们得到它们。为了解决破碎的图像,我只是做一些图像大小的搜索,如果我找不到它,并用占位符替换它。Woocommerce显示含产品图像的产品

$src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), $size); 
if (@getimagesize($src[0])) { 
    //display product image 
} else { 
    //display placeholder image 
} 

这在大多数情况下工作正常,但现在我正在将产品显示在类别中。我想先显示所有带有图像的产品,然后显示没有图像的产品。问题是一旦循环开始,如果我排除没有图像的产品,它将循环通过前12个产品,并且仅显示具有图像的12个子集。我想要它做的是保持循环,直到我有12个产品的图像(如果有12个产品的图像)。

这就是我现在没有用的东西。我一直无法代码

<?php if (have_posts()) : ?> 
    <ul class="products"> 
     <?php while (have_posts()) : the_post(); ?> 
      <?php 
       $src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), $size); 
       if (@getimagesize($src[0])) { 
        woocommerce_get_template_part('content', 'product'); 
       } 
      ?> 
     <?php endwhile; // end of the loop. ?> 
    </ul> 
<?php endif; ?> 

可能的逻辑解决方案,将忽略某些产品的循环,而(所以它会做另一奔跑如果没有图像),或以某种方式编写我的查询为一体的规定的一部分循环即坑在$ args?

任何帮助将不胜感激。

回答

1

我已经设法找到一个可行的解决方案来解决我的问题。仅仅通过单独的循环来列出产品是不可能的,而不会弄乱分页。所以合乎逻辑的步骤是使用循环,并根据图像是否存在来基本订购产品。这会产生一个新问题,因为Wordpress排序无法确定图像链接是否指向文件。

但是,您可以为woocommerce中的产品设置“菜单顺序”。然后,如果您在“Woocommerce - >设置 - >目录”下将“默认产品排序”设置为“默认排序”,它将使用此菜单顺序在产品目录视图中订购产品。

太棒了!但我仍然有17000个产品,我需要为每个产品指定一个菜单顺序。我无法使用原本需要花费数周的woocommerce工具来做到这一点。所以我决定写一个小插件,根据图像是否存在来改变每个产品的“菜单顺序”。

这里是用来写的帖子数据库的功能:

/** 
* 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 '<p>Number of products edited: <strong>'.$number_completed.'</strong>.</p>'; 
} 

我,因为我有这么多的产品我的插件处理它们在小批量。我一次管理大约2000个产品,而且没有失败。我也不得不调整我的PHP内存限制在config.php

define('WP_MAX_MEMORY_LIMIT', '256M'); 

我仍然不知道是否有可能实现这一点的,但暂时这个解决方案就足够了一个更简单的方法。