get_page_by_title()
源代码显示它只运行一个mysql查询。通过编写自定义查询,可以将函数的两个调用简化为一个查询:
global $wpdb;
$qry = "SELECT ID FROM $wpdb->posts WHERE (post_title = %s OR post_title = %s) AND post_status = \'publish\'";
$sql = $wpdb->prepare($qry, \'title1\', \'title2\' );
$res = $wpdb->get_results( $sql );
$getIDs = array();
foreach ($res as $result)
$getIDs[] = $result->ID;
$exclude = implode(\',\', $getIDs);
但是,我认为应该简化它,在其中添加缓存以减少
_posts
对于这样一件小事:
global $wpdb;
if ( false === ( $exclude = get_transient( \'myplugin_exclude\' ) ) ) {
$qry = "SELECT ID FROM $wpdb->posts WHERE (post_title = %s OR post_title = %s) AND post_status = \'publish\'";
$sql = $wpdb->prepare($qry, \'title1\', \'title2\' );
$res = $wpdb->get_results( $sql );
$getIDs = array();
foreach ($res as $result)
$getIDs[] = $result->ID;
$exclude = implode(\',\', $getIDs);
set_transient( \'myplugin_exclude\', $exclude, 60*60*24 ); // once a day
}
wp_list_pages("title_li=&exclude={$exclude}");
现在它很长,我想将其包装在函数中不会有什么坏处-有助于保持事物的整洁并有助于重用:
function get_two_pages_ids_by_titles($title1,$title2,$name) {
global $wpdb;
if ( false === ( $exclude = get_transient( $name ) ) ) {
$qry = "SELECT ID FROM $wpdb->posts WHERE (post_title = %s OR post_title = %s) AND post_status = \'publish\'";
$sql = $wpdb->prepare($qry, $title1, $title2 );
$res = $wpdb->get_results( $sql );
$getIDs = array();
foreach ($res as $result)
$getIDs[] = $result->ID;
$exclude = implode(\',\', $getIDs);
set_transient( $name, $exclude, 60*60*24 ); // once a day
}
return $exclude;
}
然后你可以简单地做:
<?php
$exclude = get_two_pages_ids_by_titles(\'title1\',\'title2\',\'listpages_exclude\');
wp_list_pages("title_li=&exclude=".$exclude);
?>
显然
get_two_pages_ids_by_titles
有点傻,太具体了。接受一个标题数组并返回一个ID会更好,但这应该有助于引导一种获取所需内容的方法。
希望这有帮助。