Wordpress add_post_meta和全局颜色数组

时间:2013-06-02 12:02:18

标签: wordpress

我想为每个新帖子(背景颜色)添加自定义css类。我这样做是通过添加add_post_data的自定义字段并在每次生成新帖子时运行该函数。

我有一个数组,其中css颜色类被定义为'blue','aqua','dark-purple'等。

一切正常但只有在生成新帖子时我无法弄清楚如何在数组中指定下一个颜色值。

同样,当使用最后一种颜色时,阵列从第一个位置重新开始。 你有想法如何实现这个目标吗?

这个功能如何知道下一个颜色是什么?是否需要查看上一篇文章?

在functions.php中:

// Define color on each new post
function set_post_color($post_ID){
    $colors = array('blue','aqua','dark-purple','red','orange','yellow','light-green','dusty-blue','bright-pink','dark-green','dusty-purple');
    $current_field_value = get_post_meta($post_ID, 'css-color-class', true);
    $value = (string)rand(0, 100); // this should be the next color in the color array

    // Only add field if it does not already exist and the post is not a revision
    if($current_field_value == '' && !wp_is_post_revision($post_ID)){
        add_post_meta($post_ID, 'css-color-class', $value, true);
    }

    return $post_ID;
}

// Hook up the function
add_action('wp_insert_post', 'set_post_color');

1 个答案:

答案 0 :(得分:1)

您有两个选项,查看数据库中分配给您上次插入的帖子的颜色,然后选择新帖子的下一个颜色,或者您可以使用下一个需要分配的颜色维护一个选项。

这有一个缺点,你需要手动维护这个实现的值,但你可以使用默认函数来获取,添加和更新选项: