WordPress 6.2 将性能要求做到更加极致,将弃用 get_page_by_title()
函数,建议开发者直接使用 WP_Query
根据标题获取页面。
为什么要弃用呢?两点原因:
get_page_by_title()
函数是直接使用数据库查询获取页面的,可能由于数据库版本或者引擎不同,而造成返回的数据会有可能不同,切换到使用WP_Query
获取数据则可确保得到相同的结果。- WordPress 6.1 的时候提高了
WP_Query
性能,实现了缓存,所以开发者直接使用 WP_Query 去根据标题获取页面则效率更高。该函数就没有必要了。
不过要特别注意的是, WP_Query
是要在插件加载完成之后才能运行,即在 plugins_loaded
的 action 之后。
那么怎么使用 WP_Query
来实现根据标题获取页面呢:
$query = new WP_Query( array( 'post_type' => 'page', 'title' => 'Sample Page', 'post_status' => 'all', 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'orderby' => 'post_date ID', 'order' => 'ASC', ) ); if ( ! empty( $query->post ) ) { $page_got_by_title = $query->post; } else { $page_got_by_title = null; }
也可以通过 get_posts()
函数来实现相同的功能,下面是使用
get_posts()
的版本:
$posts = get_posts( array( 'post_type' => 'page', 'title' => 'Sample Page', 'post_status' => 'all', 'numberposts' => 1, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'orderby' => 'post_date ID', 'order' => 'ASC', ) ); if ( ! empty( $posts ) ) { $page_got_by_title = $posts[0]; } else { $page_got_by_title = null; }