如何在wordpress中将脚本排队以仅在单个帖子和博客页面上显示?



您将如何在只想在博客和单个帖子上显示的主题中加入脚本?

我在这里检查了其他问题,但没有令人信服的答案。

我从WordPress站点获得了以下代码:

function enqueue_files() {
  if ( is_page( 'your-page' ) ) {
    // enqueue specific page script files here
  } else {
    // enqueue common scripts here
  }
}
add_action( 'wp_enqueue_scripts', 'enqueue_files' );

因此,在查看 is_page() 函数之后,我感到困惑,因为我只需要在单帖子上显示它们&博客页面,虽然以下功能仅适用于静态页面,并且由于我希望它对所有单个帖子页面和博客页面都充满活力,所以我如何才能确切地执行此操作?

<</p>

使用is_singular。它将is_page()is_single()结合在一起。链接。

它也会在attachment页面上激活。如果这是您的问题,只需使用is_page() || is_single()

您不需要传递页面/帖子slug(它实际上会打破您要完成的工作。因此,您只需:

if ( is_page() || is_single() ) {
// if ( is_singular() ) { // or this if you prefer. :)
    // enqueue specific page script files here
}

如果要检测Blogroll,请使用is_home,我认为您只针对单个帖子。

链接。

仅针对博客主页和帖子的单个帖子类型 post

function enqueue_files() {      
    if ( is_singular('post') || is_home() ) {
        // enqueue specific scripts for blog homepage and single posts of post type post
    } else {
        // enqueue common scripts here
    }
}
add_action( 'wp_enqueue_scripts', 'enqueue_files' );

说明

  • is_singular('post')检查是否正在显示指定帖子类型post的单数(感谢@umair shah yousafzai此提示)
  • is_home()确定查询是否适用于博客主页

最新更新