SQL query to include specific WooCommerce tag

2019-09-13 02:05发布

I want to modify a WooCommerce plugin in order to pick products of a selected tag of the name "right-tag" for example.

My Code is of the form:

$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 */

Can you help me?

Thanks a lot Giannis

1条回答
仙女界的扛把子
2楼-- · 2019-09-13 02:21

MySQL query to get product by specific tag:

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


Equivalent WordPress/PHP query

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;
        //...
    }
}

Both MySQL query & Code is tested and works.

Hope this helps!

查看更多
登录 后发表回答