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

最後に挿入された投稿に割り当てられた色を DB で調べてから、新しい投稿に次の色を選択するか、割り当てる必要がある次の色でオプションを維持することができます。

これには、この値を手動で維持する必要があるという欠点がありますが、デフォルトの関数を使用してオプションを取得、追加、および更新できます。

于 2013-06-02T12:11:59.573 に答える