新しい投稿ごとにカスタム 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');