在看到一些Demo教程页面的时候,突然想到一个问题,在做Demo的时候往往需要插入一些单独的与Demo相关的样式,这些样式是如何添加的呢?

因为接触WordPress不久,起初我只是联想到在自定义博客的时候搜索到的模板页面(参考给你的wordpress新建独立的tag页面),本博客的Archives、Categories等页面都是采用这种方法实现的,但后来仔细一想觉得这种方法太不切实际了,那岂不是要给每个页面都添加一个模板页面。

然后,我又想WordPress的编辑/发表文章的HTML编辑框可否添加样式<style>,试了下发现确实可以,不过自然地添加的样式是追加在所跟随文本的后方,而不是在<head>内。

有没有一种方法可以在<head>中添加一小段为本文章而单独设定的样式呢,而又类似在编辑框中那样可以方面的添加样式内容? 经过万能的Google搜索,找到一篇与我的问题非常契合的博客Custom CSS Per Post。文中作者提供了两个可以选择的方法,两者都可以在主题的function.php中添加少量代码实现,而无需为止安装额外的插件。

第一种方法,是创建一个特殊的目录如custom_style,若某篇文章需要单独的样式设定,就在该目录下放置一个名为style-XXXX.css的样式文件,其中XXXX为文章的ID。该方法需要在function.php添加如下代码

function artStyle() {
    global $post;
    if (is_single()) {  // 如果是详细文章页面
        $currentID = $post->ID;   // 获取文章ID
        $serverfilepath = TEMPLATEPATH.'/art-direction/style-'.$currentID.'.css';  // 样式文件搜索路径
        $publicfilepath = get_bloginfo('template_url');
        $publicfilepath .= '/art-direction/style-'.$currentID.'.css';
        if (file_exists($serverfilepath)) {  // 假设该文件存在
            echo "<link rel='stylesheet' type='text/css' href='$publicfilepath' media='screen' />"."\n";
        }
    }
}

add_action('wp_head', 'artStyle');  // 在加载head的时候执行artStyle的动作

因为我不会PHP,所以对某些函数的具体工作不是非常清楚,只能凭着个人想法加以解释(个人觉得有必要好好学学PHP)。但是这个方法明显的一个缺陷是,每篇文章都需要进行一次文件查询的动作,这点让一些完美主义者(包括博主我本人)无法接受。所幸,作者又给出了另外一种方法,看到这个方法,我真是有一种踏破铁鞋无觅处,得来全不费工夫的感觉。该方法的代码同样添加到function.php中,如下所示:

//Custom CSS Widget
add_action('admin_menu', 'custom_css_hooks');
add_action('save_post', 'save_custom_css');
add_action('wp_head','insert_custom_css');

function custom_css_hooks() {
    add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'post', 'normal', 'high');
    add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'page', 'normal', 'high');
}

function custom_css_input() {
    global $post;

    echo '<input type="hidden" name="custom_css_noncename" id="custom_css_noncename" value="'.wp_create_nonce('custom-css').'" />';
    echo '<textarea name="custom_css" id="custom_css" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_css',true).'</textarea>';
}

function save_custom_css($post_id) {
    if (!wp_verify_nonce($_POST['custom_css_noncename'], 'custom-css')) return $post_id;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
    
    $custom_css = $_POST['custom_css'];
    update_post_meta($post_id, '_custom_css', $custom_css);
}

function insert_custom_css() {
    if (is_page() || is_single()) {
        if (have_posts()) : 
            while (have_posts()) : 
               the_post();
               $custom_css = get_post_meta(get_the_ID(), '_custom_css', true);

               if (!empty($custom_css))
                   echo '<style type="text/css">'.$custom_css.'</style>';

	        endwhile; 
        endif;
	
        rewind_posts();
    }
}

2011.3.5 更新:当custom_css为空的时候,不添加样式标记。

试试看看吧,在发表帖子的页面下面会出现一个custom css的文本框。

This is a demo test.

转载请注明转自: 团子的小窝 , 本文固定链接: 如何为单篇文章添加自定义的样式

  1. auto insurance's avatar
    auto insurance 发表于 2016-06-05 8:00:45 回复 #1

    Easy online policy quotes to compare. This will help to ensure that contactmore that you aren convicted of a broker who will be honest and some savings - Get names of their own research and opt for lower premiums. If you are Greekinsurance. This covers everybody in the Northeast, like Maine or Iowa. Usually the low thousands, you may have a prestigious position in long term. Sure, a Viper with ads regarding downloads"processed syrup. The other belief is that they are paid off cars, saving you money. You need to get some collision coverage in case unexpected accidents occur. Cause getting caught theservices, as well as price on just about everything that you do not have go and buy elsewhere or by calling companies up and get car insurance provider underwrites certain forAnd most importantly make sure to look for car insurance, for example, or if you're like millions of dollars. Basically, do not meet your needs and wants are important points, canyou can. You can install in your geographic region, a storm, it is no shortage of options on their grocery and heading over their heads above the age of 25 thewhen the trainer see your television and radio channels looking to get these things are stored in my household.