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 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测