1

Look here:

// $term_slugs is a function argument: array('foto', 'video')

$term_query = "t.slug IN ('" . implode("','",$term_slugs) . "') ";

$ids = $wpdb->get_results($wpdb->prepare("
  SELECT
    m.meta_value
  FROM
    " . $wpdb->prefix . "posts p
    INNER JOIN " . $wpdb->prefix . "postmeta m ON m.post_id = p.ID
    INNER JOIN " . $wpdb->prefix . "term_relationships rel ON p.ID = rel.object_id
    INNER JOIN " . $wpdb->prefix . "term_taxonomy tt ON tt.term_taxonomy_id = rel.term_taxonomy_id
    INNER JOIN " . $wpdb->prefix . "terms t ON tt.term_id = t.term_id
  WHERE
    p.post_type = '%s'
    AND m.meta_key = '_thumbnail_id'
    AND p.post_status = 'publish'
    AND %s
  ORDER BY RAND()
  LIMIT 1
",
$post_type, $term_query
));

This will write something like:

WHERE
  p.post_type = 'gallery'
  AND m.meta_key = '_thumbnail_id'
  AND p.post_status = 'publish'
  AND 't.slug IN (\'foto\',\'video\') '

Shuold be:

WHERE
  p.post_type = 'gallery'
  AND m.meta_key = '_thumbnail_id'
  AND p.post_status = 'publish'
  AND t.slug IN ('foto','video') 

How to?

1 Answer 1

2

I've found an answer by myself..

(sample code)

$args_array = array($post_type);
$term_slugs = array('foto', 'video');

// create a string like '%s, %s' ecc
$placeholders = implode(', ', array_fill(0, count($term_slugs), "%s"));
$term_query = "t.slug IN ($placeholders) ";
$args_array = array_merge($args_array, $term_slugs);

$ids = $wpdb->get_results($wpdb->prepare("
  SELECT
    m.meta_value
  FROM
    " . $wpdb->prefix . "posts p
    INNER JOIN " . $wpdb->prefix . "postmeta m ON m.post_id = p.ID
    INNER JOIN " . $wpdb->prefix . "term_relationships rel ON p.ID = rel.object_id
    INNER JOIN " . $wpdb->prefix . "term_taxonomy tt ON tt.term_taxonomy_id = rel.term_taxonomy_id
    INNER JOIN " . $wpdb->prefix . "terms t ON tt.term_id = t.term_id
  WHERE
    p.post_type = '%s'
    AND m.meta_key = '_thumbnail_id'
    AND p.post_status = 'publish'
    AND $term_query
  ORDER BY RAND()
  LIMIT 1
",
$args_array // pass substitutions as an array
));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.