簡體   English   中英

將我的user_login從數據庫加載到我的acf選擇字段代碼中

[英]load my user_login from database into my acf select field code

我正在嘗試將我的user_login從數據庫上傳到acf select字段,在var_dump中我的數組結果運行良好,但是我的acf選擇字段中沒有上傳?

1.我在產品帖子中添加了自定義字段“ACF選擇字段”。

2.我正在嘗試從我的數據庫加載我的選項值。

3.我使用數組從數據庫中獲取user_login值

function.php

add_filter('acf/load_field/name=chef', 'my_acf_load_chef_field');
     function my_acf_load_chef_field( $field )
{   
    $user_fields = array( 'user_login');
    $argu = new WP_User_Query( array( 'role' => 'chef' , 'fields' => $user_fields ));
    $choices = $argu->get_results();
    $field = array();  
     if( is_array($choices) ) {
        $len = count($choices);
        for($i = 0; $i < $len; $i++) {
            array_push($field, ($choices[$i]->user_login));
    }
   }
    // var_dump($field);
    // exit;
    return $field;
}

這是var_dump結果

array(5) { 
[0]=> string(5) "Ahmed" 
[1]=> string(5) "Khedr" 
[2]=> string(4) "meme" 
[3]=> string(5) "Menna" 
[4]=> string(7) "mustafa" } 

this is the array result that i want to load in acf field

您不會將您的選擇分配給該字段。 試試這段代碼:

if (is_array($choices)) {
    // Clear the choices
    $field[‘choices’] = [];

    // Assign the data to the field
    foreach ($choices as $choice) {
       $field[‘choices’][$choice->user_login] = $choice->user_login;
    }
}

我發現 這是新代碼感謝justkidding96

add_filter('acf/load_field/name=chef', 'my_acf_load_chef_field');

function my_acf_load_chef_field( $field )
{    
    $user_fields = array( 'user_login');
    $argu = new WP_User_Query( array( 'role' => 'chef' , 'fields' => $user_fields ));
    $choices = $argu->get_results();
    //$choices = get_field($field['choices'], $post->ID , false);
    $field['choices'] = array();  
     if( is_array($choices) ) {
        $len = count($choices);
        for($i = 0; $i < $len; $i++) {
            array_push($field['choices'], ($choices[$i]->user_login));
    }
   }
    // var_dump($field['choices']);
    // exit;
    return $field;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM