网站优化

网站优化

Products

当前位置:首页 > 网站优化 >

Wordpress:wpdb准备条件

GG网络技术分享 2025-03-18 16:12 3


问题描述:

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)

}

标签:

提交需求或反馈

Demand feedback