2017-08-16 96 views
0

試圖編寫一段代碼來擴展我在Wordpress中使用的主題。獲取自定義文章並放入選項數組 - wordpress插件

基本上,我想獲得所有自定義帖子類型,並把它放入一個選擇數組 - 我遇到的問題是,我需要在數組中添加選項值,我不能把foreach循環放在數組,所以不知道如何做到這一點。

在下面的代碼,你會看到代碼:

'options'   => array(), 

這就是自定義信息必須在格式:

'PostID' => esc_html__('Post Name', 'builder'), 

這裏是我的代碼:

function get_fields() {   

    $fields = array(
        'get_post_names' => array(
      'label'   => esc_html__('Url Opens', 'builder'), 
      'type'   => 'select', 
      'option_category' => 'configuration', 
      'options'   => array(), 
      'toggle_slug'  => 'post_names', 
      'description'  => esc_html__('Here you can choose whether or not your link opens in a new window', 'et_builder'), 
      ), 
    ); 

     global $wpdb; 
     $custom_post_type = 'custom_post_name'; 
     $results = $wpdb->get_results($wpdb->prepare("SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type), ARRAY_A); 
     if (! $results) 
      return; 

     foreach($results as $index => $post) { 
     $fields['options'][] = array (
      $post['ID'] => esc_html__($post['post_title'], 'builder'), 
     ); 
     } 

      return $fields; 

     } 

任何幫助將不勝感激。

感謝

回答

0

但願這可能工作

function generate_post_select($select_id, $post_type, $selected = 0) { 
     $post_type_object = get_post_type_object($post_type); 
     $label = $post_type_object->label; 
     $posts = get_posts(array('post_type'=> $post_type, 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1)); 
     foreach ($posts as $post) { 
      echo $post->post_title; 
     } 
    } 

$select_id用作名稱和選擇的ID,$post_type是你想要的類型被製作成選擇和$selected是的帖子ID你想在選擇框中選擇。

+0

對不起,沒有幫助,因爲不在陣列中 –

0

找到了一個解決方案,如果有人想知道。

將「選項」更改爲以下內容並從全局$ wpdb中刪除了代碼;下。

'options'   => array_reduce(get_posts('post_type=custom_post&posts_per_page=-1'), function($result, $item) { 
     $result[$item->ID] = $item->post_title; 
     return $result; 
    }),