我在我的 WordPress 项目中使用函数 get_page_by_title 但它已被弃用。 我尝试关闭 WP_DEBUG 但仍然不起作用。
我的语言文件夹结构: - - -语言 ---------ja.json ---------en.json
文件 ja.json
{
"page-title": "page title - ja",
}
文件 en.json
{
"page-title": "page title",
}
我在 example-page.php 中使用 get_page_by_title ,例如:
$pageId= get_page_by_title(lang('page-title'))->ID;
我的方法是使用 WP_Query ,如下所示。
function get_page_id_by_title($title) {
$query = new WP_Query(array(
'meta_query' => array(
array(
'key' => 'name',
'value' => $title,
'compare' => '=',
),
),
));
if ($query->have_posts()) {
$query->the_post();
$page_id = get_the_ID();
wp_reset_postdata();
return $page_id;
} else {
return null;
}
}
但是出了问题
需要一个像 get_page_by_title 一样工作的函数
基于 How to get page URL by title in WordPress? 接受的答案代码,您可以按如下方式构建自定义函数:
function get_page_id_from_title( $title ) {
$page_ids = (array) get_posts([
'title' => $title,
'post_type' => 'page',
'fields' => 'ids',
]);
return empty($page_ids) ? null : min($page_ids);
}
代码位于活动主题的functions.php 文件中(或插件中)。已测试并有效。