You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在functions.php中扩展get_post_field查询以使用页面别名数组?

问题分析与修复

错误原因

  • 比较逻辑完全错误:get_post_field('post_name', get_the_ID())返回的是当前页面的别名字符串,你用===直接和数组做比较,字符串与数组类型不匹配,条件永远无法成立。
  • 数组格式写错:array(['contact-us', 'about-us'])生成的是二维数组(数组嵌套数组),但我们只需要存储页面别名的一维数组。
  • 匹配方式不对:判断字符串是否存在于数组中,必须用PHP的in_array()函数,而非相等运算符。

修复后的代码

function alerts_enqueue() {
    $current_screen = get_current_screen(); 
    // 定义要匹配的页面别名一维数组
    $target_pages = ['contact-us', 'about-us'];
    // 用in_array检查当前页面别名是否在目标数组内
    if ('post' === $current_screen->base && in_array(get_post_field('post_name', get_the_ID()), $target_pages)) {
       wp_enqueue_script('alert-script', get_stylesheet_directory_uri() . '/js/alerts.js', array(), null, true); 
   }
}
add_action('enqueue_block_editor_assets', 'alerts_enqueue');

额外提示

如果需要更严谨的类型校验,可以给in_array()加上第三个参数true,确保页面别名的字符串类型和数组元素完全一致:

in_array(get_post_field('post_name', get_the_ID()), $target_pages, true)

内容的提问来源于stack exchange,提问作者Daniel Ford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 15:07:36