2016-08-03 49 views
1

我有一個需要在自定義帖子類型的wp_postmeta表中保存/檢索的對象的集合。使用WordPress發佈元數據功能的HTML表單中的關聯數組

結構示例:

array(
    array( 
     'firstname' => 'Johnny', 
     'middlename' => 'William' 
    ), 
    array( 
     'firstname' => 'Jane', 
     'middlename' => 'Alice' 
    ) 
) 

我希望能夠通過這樣的對象進行迭代:

$children = get_post_meta($postid, '_children', true); 

$arrlength = count($children); 
for($x = 0; $x < $arrlength; $x++) 
{ 
    echo '<input type="text" name="_children[][firstname]" id="_children[][firstname]" value="' . $meta_values['_children'][0][$x][firstname] . '" /><br />'; 
    echo '<input type="text" name="_children[][middlename]" id="_children[][middlename]" value="' . $meta_values['children'][0][$x][middlename] . '" /><br />'; 
} 

我不認爲以上是正確的。我試圖讓與保存在save_post行動發佈數據:

function test_meta_save($post_id) { 

    // Checks save status 
    $is_autosave = wp_is_post_autosave($post_id); 
    $is_revision = wp_is_post_revision($post_id); 
    $is_valid_nonce = (isset($_POST[ '_children_nonce' ]) && wp_verify_nonce($_POST[ '_children_nonce' ], basename(__FILE__))) ? 'true' : 'false'; 

    // Exits script depending on save status 
    if ($is_autosave || $is_revision || !$is_valid_nonce) { 
     return; 
    } 
    if(isset($_POST[ '_children' ])) { 
     update_post_meta($post_id, '_children', array_map('sanitize_text_field', $_POST[ '_children' ]); 
    } 
} 
add_action('save_post', 'test_meta_save'); 

我知道上面是不正確的要麼。

+1

PL輕鬆嘗試'$ meta_values ['_ children'] [$ x] [firstname]'只需刪除'[0]'! –

+0

@IsmailRBOUH我想知道那個[0]。數據庫顯示的值爲NULL,所以我認爲在我發佈的'post_save'代碼行中存在問題。 – rwkiii

+0

'$ _POST ['_children']'是一個數組嗎?你如何輸入初始值! –

回答

1

在這裏,你有你的最後一個問題,但這次get_post_meta()其中最後一個參數應該是false同樣的問題。因爲你是閱讀/創建arrays值和不是strings值。

在您的代碼:

$children = get_post_meta($postid, '_children', true); 

您需要刪除最後一個參數在get_post_meta()功能,默認值是false
相反,你將擁有:

$children = get_post_meta($postid, '_children'); 

$arrlength = count($children); 
for($x = 0; $x < $arrlength; $x++) 
{ 
    echo '<input type="text" name="_children[][firstname]" id="_children[][firstname]" value="' . $meta_values['_children'][0][$x][firstname] . '" /><br />'; 
    echo '<input type="text" name="_children[][middlename]" id="_children[][middlename]" value="' . $meta_values['children'][0][$x][middlename] . '" /><br />'; 
} 

參考文獻:

+0

我在你的'for'循環中看到你指定了一個額外的維度。您引用的'[0]'維度是將get_post_meta()最後一個參數設置爲false的效果?感謝您的解釋和參考。 – rwkiii