php - SQL 查询包含特定的 WooCommerce 标签

标签 php mysql sql wordpress woocommerce

我想修改 WooCommerce 插件,以便选择名称为“right-tag”的选定标签的产品。

我的代码的形式为:

$query =$wpdb->prepare(  "SELECT * FROM " . $wpdb->prefix . "posts  WHERE `post_type` LIKE 'product' AND `post_status` LIKE 'publish'",0);
/* do something */
foreach ($result as $index => $prod) {

    $sql = $wpdb->prepare(  "SELECT *
    FROM " . $wpdb->prefix . "postmeta
    WHERE `post_id` =" . $prod->ID . " AND `meta_key` LIKE '_stock_status';",0);
    /* do something */
    /* do something */

你能帮我吗?

非常感谢 扬尼斯

最佳答案

MySQL 查询以按特定标签获取产品:

SELECT posts.ID AS product_id,
       posts.post_title AS product_title
FROM wp_posts AS posts,
     wp_terms AS terms,
     wp_term_relationships AS term_relationships,
     wp_term_taxonomy AS term_taxonomy
WHERE term_relationships.object_id = posts.ID
  AND term_taxonomy.term_id = terms.term_id
  AND term_taxonomy.term_taxonomy_id = term_relationships.term_taxonomy_id
  AND posts.post_type = 'product'
  AND posts.post_status = 'publish'
  AND term_taxonomy.taxonomy = 'product_tag'
  AND terms.slug = 'my-tag-1'; -- Replace it with your product tag

<小时/> 等效的 WordPress/PHP 查询

global $wpdb;
$query = "SELECT posts.ID AS product_id,
            posts.post_title AS product_title
     FROM {$wpdb->prefix}posts AS posts,
          {$wpdb->prefix}terms AS terms,
          {$wpdb->prefix}term_relationships AS term_relationships,
          {$wpdb->prefix}term_taxonomy AS term_taxonomy
     WHERE term_relationships.object_id = posts.ID
       AND term_taxonomy.term_id = terms.term_id
       AND term_taxonomy.term_taxonomy_id = term_relationships.term_taxonomy_id
       AND posts.post_type = 'product'
       AND posts.post_status = 'publish'
       AND term_taxonomy.taxonomy = 'product_tag'
       AND terms.slug = 'my-tag-1';"; //Replace it with your product tag
$products = $wpdb->get_results($query);

if (!empty($products))
{
    //looping through all the products
    foreach ($products as $key => $product)
    {
        //...
        $product->product_id;
        $product->product_title;
        //...
    }
}

MySQL 查询和代码都经过测试并且可以工作。

希望这有帮助!

关于php - SQL 查询包含特定的 WooCommerce 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920234/

相关文章:

php - Div 有莫名其妙的巨大右边距?

debian - 如何在 Debian wheezy 操作系统中安装 MySQL WorkBench?

java - 如何使用远程服务器上的mysql数据库创建连接池?

php - Woocommerce:获取产品的所有订单

php - 禁用 max_user_connections 限制

php - .php 与 HTML 对比 .html 与 PHP

php - Symfony 项目设计模式

mysql - Laravel:查询返回错误结果

sql - 我应该使用 sp_executesql 还是 EXEC 来运行存储过程?

php - 查询 PHP 信号量而不阻塞?