简体   繁体   中英

Get Custom Posts and put into option array - wordpress plugin

Trying to write a piece of code to expand a theme that I am using in Wordpress.

Basically, I want to get all custom post types and put it into an array for a select - the issue I am having is that I need to add the option values in the array and I cannot put a foreach loop in the array so not sure how to do this.

In the code below you will see the code:

'options'         => array(),

This is where the custom posts need to be in the format:

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

Here is my code:

  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;

      }

Any help would be much appreciated.

Thanks

Hopefully this may work

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 is used as the name and id of the select, $post_type is the type you want to be made into the select and $selected is the post id you want selected in the select box.

Found a solution if anyone wants to know.

Changed the 'option' to be the following and removed the code from global $wpdb; down.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM