zoukankan      html  css  js  c++  java
  • 为WordPress某个文章添加额外的样式

    如需把css直接写在某文章,把下面代码放如function.php

    /*
    为特定文章添加特定css最简单的方式.
    */
    /*添加自定义CSS的meta box*/
    add_action('admin_menu', 'cwp_add_my_custom_css_meta_box');
    /*保存自定义CSS的内容*/
    add_action('save_post', 'cwp_save_my_custom_css');
    /*将自定义CSS添加到特定文章(适用于Wordpress中文章、页面、自定义文章类型等)的头部*/
    add_action('wp_head','cwp_insert_my_custom_css');
    function cwp_add_my_custom_css_meta_box() {
        add_meta_box('my_custom_css', '自定义CSS', 'cwp_output_my_custom_css_input_fields', 'post', 'normal', 'high');
        add_meta_box('my_custom_css', '自定义CSS', 'cwp_output_my_custom_css_input_fields', 'page', 'normal', 'high');
    }
    function cwp_output_my_custom_css_input_fields() {
        global $post;
        echo '<input type="hidden" name="my_custom_css_noncename" id="my_custom_css_noncename" value="'.wp_create_nonce('custom-css').'" />';
        echo '<textarea name="my_custom_css" id="my_custom_css" rows="5" cols="30" style="100%;">'.get_post_meta($post->ID,'_my_custom_css',true).'</textarea>';
    }
    function cwp_save_my_custom_css($post_id) {
        if (!wp_verify_nonce($_POST['my_custom_css_noncename'], 'custom-css')) return $post_id;
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
        $my_custom_css = $_POST['my_custom_css'];
        update_post_meta($post_id, '_my_custom_css', $my_custom_css);
    }
    function cwp_insert_my_custom_css() {
        if (is_page() || is_single()) {
            if (have_posts()) : while (have_posts()) : the_post();
            echo '<style type="text/css">'.get_post_meta(get_the_ID(), '_my_custom_css', true).'</style>';
            endwhile; endif;
            rewind_posts();
        }
    }

    大致原理:以post meta的方式在文章的发布/编辑页面添加自定义输入栏用以输入自定义的css,在文章详情页载入前述输入的css。

    然后编辑文章时就会看见自定义css编辑框

    输入样式试试

    查看文章头部输出,成功!

     

  • 相关阅读:
    mongodb
    python中读取文件的read、readline、readlines方法区别
    uva 129 Krypton Factor
    hdu 4734
    hdu 5182 PM2.5
    hdu 5179 beautiful number
    hdu 5178 pairs
    hdu 5176 The Experience of Love
    hdu 5175 Misaki's Kiss again
    hdu 5174 Ferries Wheel
  • 原文地址:https://www.cnblogs.com/tinyphp/p/5861196.html
Copyright © 2011-2022 走看看