简体   繁体   中英

wordpress custom query to select a meta value

SELECT b.post_title, a.post_id, COUNT( * ) as Total
FROM  wp_posts b INNER JOIN 
            wp_postmeta a ON a.post_id = b.ID
    WHERE a.meta_value = 1
      AND a.meta_key = 'type-select' 
      AND b.post_status = 'publish'
      and post_type = 'car-cc'
GROUP BY b.post_title, a.post_id

Currently it select's post title and post id but i also need to select a meta value where meta key = type-gen the problem is another meta key is already compared in the query.

SQL Fiddle: http://sqlfiddle.com/#!2/109c2/1

Here you go

SELECT b.post_title, a.post_id, COUNT( * ) AS Total,
(SELECT meta_value FROM  `wp_postmeta` WHERE post_id= b.ID AND meta_key='type-gen') AS 'new  meta value'
FROM  wp_posts b INNER JOIN 
            wp_postmeta a ON a.post_id = b.ID
    WHERE a.meta_value = 1
      AND a.meta_key = 'type-select' 
      AND b.post_status = 'publish'
      AND post_type = 'car-cc'
GROUP BY b.post_title, a.post_id

Fiddle

SELECT b.post_title, a.post_id, COUNT( * ) as Total
FROM  wp_posts b INNER JOIN 
            wp_postmeta a ON a.post_id = b.ID
    WHERE (a.meta_value = 1
      AND a.meta_key = 'type-select' 
      AND b.post_status = 'publish'
      and post_type = 'car-cc') 
    OR (a.meta_value = 1
      AND a.meta_key = 'type-gen' 
      AND b.post_status = 'publish'
      and post_type = 'car-cc')
GROUP BY b.post_title, a.post_id

Use WP_Query for this,

Modified from the Codex page

$args = array(
  'post_type' => 'car-cc',
  'meta_query' => array(
    array(
      'key' => 'type-select',
      'value' => '1',
      'compare' => '='
),
    array(
      'key' => 'type-gen',
      'value' => 'my-great-type',
      'compare' => 'LIKE'
    )
  )
);

$query = new WP_Query( $args );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM