我想要做的是创建一个wordpress函数,从一个page_ids列表中获取page_slugs,并将它们作为一个字符串存储在一个变量中,然后我就可以从另一个函数中简单地“回显”/“调用”。
到目前为止,我可以使用以下方法从一个page_id中获得一个page_slug:
$the_page_slug = 'test';
global $wpdb;
$page_id_from_slug = '\'' . $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name ='".$the_page_slug."'") . '\'';
echo $page_id_from_slug;
result is ok: '12'
这个函数也能工作。
function id_from_slug($the_page_slug){
global $wpdb;
$page_id_from_slug = '\'' . $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name ='".$the_page_slug."'") . '\'';
return $page_id_from_slug;
}
echo id_from_slug('test');
result is ok: '12'
问题是,我无法让它与一个page_slugs数组一起工作。
我的数据如下:
$the_page_slugs = array('test', 'test-nr4', 'test-9', 'sample4', 'sample-nr12');
回波输出(page_ids)应该如下所示:
'12','16','54','76','123‘
有什么想法吗?
发布于 2014-09-03 14:53:30
试试下面这样的方法。
global $wpdb;
$the_page_slugs = array('test', 'test-nr4', 'test-9', 'sample4', 'sample-nr12');
$page_id_from_slug = '\'' . $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name in '" . implode("','",$the_page_slugs) . "'") . '\'';
echo $page_id_from_slug;
发布于 2014-09-05 07:49:11
所以这是我的解决方案,很好,这正是我需要它的方式。看看代码,看看我更改了什么/添加了什么:
IN()和内爆()提示确实是我所需要的,在将"get_vars“(只得到一个结果)更改为"get_results”之后,稍微调整一下它就可以了。
这是我的代码,肯定可以改进.
// code to get page_ids from page_slugs
// the list of page_slugs
$the_page_slugs = array('test', 'test-re', '1234', 'test-56', 'sample34', 'me3-uc', '1-12987-db', 'thy-m2o-1873');
// set global, just in case ;)
global $wpdb;
// query to get the page_ids
$sql = "SELECT ID FROM wp_posts WHERE post_name IN('" . implode("', '", $the_page_slugs) . "') AND post_status = 'publish'";
//this calls the query
$get_page_ids = $wpdb->get_results($wpdb->prepare($sql));
//prepare new var
$the_page_ids ='';
//loop thru results to create var
foreach($get_page_ids as $get_page_ids_result){
//formate results, need it comma separated
$the_page_ids .= ('' == $the_page_ids ) ? '':', ';
//fill it
$the_page_ids .= $get_page_ids_result->ID;
}
echo "check if result is what we need<br/>";
echo $the_page_ids;
//perfekt result, looks like: 325, 323, 324, 327, 328, 329, 334, 335
谢谢你的帮助。
发布于 2014-09-03 14:54:54
将sql更改为:
"SELECT ID FROM $wpdb->posts WHERE post_name in (".implode(",",$the_page_slugs)."))";
在从数据库中获得成功后,它将有一系列关于print_r
成功的记录。
https://stackoverflow.com/questions/25647308
复制相似问题