I'm trying to use sql->prepare
with many strings concatenation.
In my code below, I try to call a function which will return me an array of get_post
from $wpdb->prepare
.
function test($array){
$sqlprep = "SELECT SQL_CALC_FOUND_ROWS p.ID
FROM {$wpdb->prefix}posts p
LEFT JOIN {$wpdb->prefix}postmeta m ON m.post_id = p.ID
LEFT JOIN {$wpdb->prefix}term_relationships r ON (p.ID = r.object_id)
LEFT JOIN {$wpdb->prefix}term_relationships r1 ON (p.ID = r1.object_id)
LEFT JOIN {$wpdb->prefix}term_relationships r2 ON (p.ID = r2.object_id)
LEFT JOIN {$wpdb->prefix}term_taxonomy tt ON tt.term_taxonomy_id = r.term_taxonomy_id
LEFT JOIN {$wpdb->prefix}terms t ON t.term_id = tt.term_id AND t.term_id = r.term_taxonomy_id
WHERE 1=1";
if(isset($array['post_type']) && !empty($array['post_type']){
$sqlprep .= " AND p.post_type = '".$array['post_type']."'";
}
if(isset($array['post_type']) && !empty($array['post_type']){
$sqlprep .= " AND p.post_type = '".$array['post_status']."'";
}
$sql = $wpdb->prepare($sqlprep);
$ids = $wpdb->get_col($sql);
return array_map('get_post', $ids)
}
and the value is an array which is :
$args=array(
'post_type' => 'post',
'post_status' => 'published',
);
When I try to print_r($sql)
to get the query, it always just stop till WHERE 1=1
.
Can string concatenation be used for wpdb prepare
?
Pay attention to the use of the properties in the $wpdb object and the use of the prepare method, furthermore there is an issue with the column name for the post_status:
function test($array){
$sql = "SELECT SQL_CALC_FOUND_ROWS p.ID
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->postmeta} m ON m.post_id = p.ID
LEFT JOIN {$wpdb->term_relationships} r ON (p.ID = r.object_id)
LEFT JOIN {$wpdb->term_relationships} r1 ON (p.ID = r1.object_id)
LEFT JOIN {$wpdb->term_relationships} r2 ON (p.ID = r2.object_id)
LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = r.term_taxonomy_id
LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id AND t.term_id = r.term_taxonomy_id
WHERE 1=1";
if(isset($array['post_type']) && !empty($array['post_type']){
$sql .= $wpdb->prepare(" AND p.post_type = %s", $array['post_type']);
}
if(isset($array['post_type']) && !empty($array['post_type']){
$sql .= $wpdb->prepare(" AND p.post_status = %s", $array['post_status']);
}
$ids = $wpdb->get_col($sql);
return array_map('get_post', $ids)
}