dourang6858 2018-08-09 11:06
浏览 46


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.

  • 写回答

1条回答 默认 最新

  • dp815292 2018-08-09 11:10

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on发生意外错误: 5无法连接到 MQTT 代理,如何解决?