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

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

问题描述:

I am creating posts with the wp_insert_post() function. For certain post categories, I need to dynamically add CSS & JS into the post. Is there any inbuilt function or 3rd party plugins through which I could do that?

I tried wp_enqueue_* functions, using child themes but they apply scripts to all posts irrespective of categories.

我正在使用wp_insert_post()函数创建帖子。 对于某些帖子类别,我需要动态添加CSS& JS进入帖子。 是否有任何内置函数或第三方插件可以通过我做到这一点? p>

我尝试了wp_enqueue_ *函数,使用子主题,但它们将脚本应用于所有帖子而不管其类别。 p > div>

You need to use separate template file for your category. Take a look at Wordpress templates hierarchy, you will most likely need to use category-$slug.php template. In this template file you will need to use regular wp_enqueue_xxx functions to inject JS / CSS that you need for this particular category.

UPDATE: To be able to apply additional JS / CSS to posts that have certain category instead of category itself you need to use wp_get_post_categories() function to retrieve list of categories for your post, then decide if you have required category in the list and if it is so - apply additional assets. It can look something like this:

// 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 ...

}

Of course this code should reside into template that renders post e.g. in single.php