dourang6858 2018-08-09 11:06
浏览 46
已采纳

如何在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.

  • 写回答

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 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法