0

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

我有一个数组,其中 css 颜色类定义为“蓝色”、“浅绿色”、“深紫色”等。

一切正常,只是我不知道在生成新帖子时如何在数组中分配下一个颜色值。

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

这个函数怎么知道下一个颜色是什么?是否需要偷看上一篇文章?

在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');
4

1 回答 1

1

您有两个选择,在数据库中查找分配给您最后插入的帖子的颜色,然后为您的新帖子选择下一种颜色,或者您可以保留一个带有您需要分配的下一种颜色的选项。

这样做的缺点是您需要手动维护这个值,但您可以使用默认函数来获取、添加和更新选项:

于 2013-06-02T12:11:59.573 回答