首页 > 解决方案 > SQL 从数据库中获取 Woocommerce 产品缩略图

问题描述

过去两天我一直在寻找 Woocommerce 产品缩略图(图像)文本和 URL 存储在数据库表中的确切位置,但仍然无法弄清楚!

我处于必须使用 SQL 查询将产品数据移动到另一个表中的情况,并且我必须从我的 phpmyadmin 面板中实现该过程。

我已经搜索了 wp_posts 和wp_postmeta表格,其中包含产品wp_posts 的指南列,到目前为止,我知道通常该帖子将其缩略图链接存储在其中一个类型为 的帖子中,而我需要带有 a 的帖子或者像这样。urlpost_type like 'product%'attachmentpost_typeproduct

希望我能在这里找到一些答案,谢谢。

标签: phpmysqldatabasewordpresswoocommerce

解决方案


您可以使用 Wordpress WP_Query 来获取产品的缩略图。

$args = array(
        'post_type'      => 'product',   //post type of product
        'posts_per_page' => -1
    );

    $query= new WP_Query( $args );

    while ( $query->have_posts() ) : $query->the_post();
        global $product;
      //woocommerce_get_product_thumbnail is use to get the product thumbnail link
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();

解决方案 2 - 使用您在查询中提到的自定义查询。

//Using custom query get the details from wp_postmeta and wp_posts
//_wp_attached_file - meta key for image
$querystr = "SELECT p.*, pm2.meta_value as product_image FROM wp_posts p LEFT JOIN
wp_postmeta pm ON (
pm.post_id = p.id
AND pm.meta_value IS NOT NULL
AND pm.meta_key = '_thumbnail_id'
)
LEFT JOIN wp_postmeta pm2 ON (pm.meta_value = pm2.post_id AND pm2.meta_key = '_wp_attached_file'
AND pm2.meta_value IS NOT NULL) WHERE p.post_status='publish' AND p.post_type='product'
ORDER BY p.post_date DESC";



$upload_dir   = wp_upload_dir();
//get wp_upload url
$wp_upload_url = $upload_dir['baseurl'];
$pageposts = $wpdb->get_results($querystr, OBJECT);
foreach ($pageposts as $post){

        echo "<br /><a href='".$post->guid."'><img src='". $wp_upload_url.'/'.$post->product_image."'>".$post->post_title."</a>";

}

推荐阅读