【问题标题】:WooCommerce get product Image from Category IDWooCommerce 从类别 ID 获取产品图片
【发布时间】:2015-03-02 08:07:59
【问题描述】:

我整个周末都在为此苦苦挣扎,我已经阅读了 100 篇文章/教程,但我似乎无法做到这一点。基本上我有一个类别 ID,我想在类别页面上获取该类别的随机图像。例如,我有 Jumper 类别(cat id 1),我想从 cat id 1 的帖子中获取随机图像。此刻我收到了数百张相同的图像返回。

这是我创建的代码:

$args = array(
    'posts_per_page' => 1,
    'post_type' => 'product',
    'tax_query'     => array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'id', 
            'terms'     => $category->term_id
        )
    )
);

$myposts = new WP_Query( $args );

foreach ( $myposts as $post ) : setup_postdata( $post );

         $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); 
         //$image = wp_get_attachment_image_src($mypost->ID, 'woo-size-category');
         the_title();
         echo '<img src="' .esc_url($image[0]). '" alt="' . esc_attr($category->name).'"  />';
endforeach;

这是整个内容-product_cat.php:

<?php
/**
 * The template for displaying product category thumbnails within loops.
 *
 * Override this template by copying it to yourtheme/woocommerce/content-product_cat.php
 *
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     1.6.4
 */
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

global $woocommerce_loop;

// Store loop count we're currently on
if (empty($woocommerce_loop['loop']))
    $woocommerce_loop['loop'] = 0;

// Increase loop count
$woocommerce_loop['loop'] ++;

$thumbnail_id = get_woocommerce_term_meta($category->term_id, 'thumbnail_id', true);
$cat = 'no_image';
if ($thumbnail_id) {
    $cat = 'has_image';
}
?>
<div class="product-category product col-lg-3 element <?php echo $cat; ?>">



    <a href="<?php echo get_term_link($category->slug, 'product_cat'); ?>">

        <?php
        /**
         * woocommerce_before_subcategory_title hook
         *
         * @hooked woocommerce_subcategory_thumbnail - 10
         */
        if ($thumbnail_id) {
            $image = wp_get_attachment_image_src($thumbnail_id, 'woo-size-category');
            echo '<img src="' . esc_url($image[0]) . '" alt="' . esc_attr($category->name) . '"  />';
        } else {


$args = array(
    'posts_per_page' => 1,
    'post_type' => 'product',
    'tax_query'     => array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'id', 
            'terms'     => $category->term_id
        )
    )
);

$myposts = new WP_Query( $args );

foreach ( $myposts as $post ) : setup_postdata( $post );

         $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); 
         //$image = wp_get_attachment_image_src($mypost->ID, 'woo-size-category');
         the_title();
         echo '<img src="' .esc_url($image[0]). '" alt="' . esc_attr($category->name).'"  />';
endforeach;
        }

        ?>

        <div class="category-info">
            <h2><?php echo jwUtils::crop_length($category->name, jwOpt::get_option('letter_excerpt_cat_title', -1)); ?></h2>
            <?php if (jwOpt::get_option('woo_number_of_items', '1') == '1') { ?>
                <span class="count_items"><?php echo $category->count . ' ' . __('Items', 'jawtemplates'); ?></span>
            <?php } ?>
        </div>


    </a>


</div>

很高兴知道这不起作用的原因。任何帮助将不胜感激!

谢谢 克里斯

***** 更新 - 这是 Var Dump *****

24array(1) { [0]=> object(WP_Post)#9805 (24) { ["ID"]=> int(12738) ["post_author"]=> string(1) "1" ["post_date"]=> string(19) "2015-02-16 15:27:06" ["post_date_gmt"]=> string(19) "2015-02-16 15:27:06" ["post_content"]=> string(80) "The Jungle Race is a serious event for Tiger. When the other animals don't train" ["post_title"]=> string(23) "The Tiger Who Was Angry" ["post_excerpt"]=> string(80) "The Jungle Race is a serious event for Tiger. When the other animals don't train" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(4) "open" ["post_password"]=> string(0) "" ["post_name"]=> string(23) "the-tiger-who-was-angry" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2015-02-23 21:02:42" ["post_modified_gmt"]=> string(19) "2015-02-23 21:02:42" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(0) "" ["menu_order"]=> int(0) ["post_type"]=> string(7) "product" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } }

图像是生成的,但不是来自正确的类别

********解决方案********

这就是我最终得到的结果(工作!)

if ($thumbnail_id) {
    $image = wp_get_attachment_image_src($thumbnail_id, 'woo-size-category');
    echo '<img src="' . esc_url($image[0]) . '" alt="' . esc_attr($category->name) . '"  />';
} else {

global $wpdb;

// Get a random product from this category
$args = 'SELECT object_id
FROM `wp_term_relationships`
where term_taxonomy_id = '.$category->term_id.' order by rand() limit 1';

$random_product_in_cat = $wpdb->get_var( $args );


// Get the returned post thumbnail
$image = wp_get_attachment_url( get_post_thumbnail_id($random_product_in_cat) );
echo '<img src="' . esc_url($image) . '" alt="' . esc_attr($category->name) . '"  />';
}

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    我会通过get_posts() 创建一组帖子,然后随机选择一个。我没有对此进行测试,但这是概念:

    // Get a random product from this category
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 1,
        'category'  => $category->cat_ID,
        'orderby' => 'rand',
    );
    $random_product_in_cat = get_posts( $args );
    
    // Get the returned post thumbnail
    echo get_the_post_thumbnail( $random_product_in_cat[0]->ID, 'thumbnail' );
    

    【讨论】:

    • 您好,感谢您的回复,不幸的是,这似乎不起作用。由于某种原因,它似乎没有选择任何帖子
    • 你在哪里调用它(在什么文件中)? $category-&gt;cat_ID 可能是 null
    • 它在我的主题目录中。我检查过 $category->cat_ID 工作正常。
    • $random_product_in_cat[0]->ID;绝对是空白。再次感谢您的帮助
    • 如果您在运行查询后var_dump($random_product_in_cat) 怎么办?
    猜你喜欢
    • 2015-05-27
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 2017-04-01
    • 2014-01-27
    • 2016-12-05
    相关资源
    最近更新 更多