如何在 PHP 中创建 wordpress 帖子时以编程方式和动态添加 CSS & JS

How to programatically & dynamically add CSS & JS while creating wordpress posts in PHP

我正在使用 wp_insert_post() 函数创建 posts。对于某些 post 类别,我需要将 CSS 和 JS 动态添加到 post 中。是否有任何内置功能或第三方插件可以让我做到这一点?

我尝试了 wp_enqueue_* 函数,使用子主题,但它们将脚本应用于所有 post,而不考虑类别。

您需要为您的类别使用单独的模板文件。看看 Wordpress templates hierarchy,您很可能需要使用 category-$slug.php 模板。在此模板文件中,您将需要使用常规 wp_enqueue_xxx 函数来注入 JS / CSS,您需要用于此特定类别。

更新: 能够将额外的 JS / CSS 应用到具有特定类别[=25= 的 post ] 而不是类别本身,您需要使用 wp_get_post_categories() 函数来检索 post 的类别列表,然后确定列表中是否有所需的类别,如果是这样 - 应用其他资产。它看起来像这样:

// Assuming that we have ID of current post inside $postId variable
// that can be retrieved e.g from $postId = the_post()->ID
// or from global $post variable
//
// Also assuming that we have $slug variable that contains slug
// of the category, we need to apply additional JS / CSS to
// 
// Example:
// $postId = 123;
// $slug = 'hairstyle'; 

$categories = wp_get_post_categories($postId);
if (is_array($categories) && array_reduce(array_filter(array_map('get_category', $categories), function ($category) {
        /** @var \WP_Term $category */
        return $category->slug;
    }), function ($found, $category) use ($slug) {
        return $found ?: $category === $slug;
    }, false)) {

    // ... Apply additional JS / CSS ...

}

当然,这段代码应该驻留在呈现 post 的模板中,例如在 single.php