获取自定义帖子并放入选项数组 - wordpress插件

时间:2017-08-16 09:05:53

标签: php arrays wordpress loops foreach

尝试编写一段代码来扩展我在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;

      }

非常感谢任何帮助。

由于

2 个答案:

答案 0 :(得分: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用作select的名称和ID,$post_type是您要在select中添加的类型,$selected是您要在其中选择的帖子ID选择框。

答案 1 :(得分: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;
    }),
相关问题