1

I am making a WordPress plugin and hit a rough point. I'm trying to make it so a user can select from all their post types, including custom post types. The code I have below shows the post, page, and attachment post types in a dropdown in the WordPress admin.

<?php
$args = array(
    'public'   => true,
    '_builtin' => true
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator ); 
echo '<select name="custom-post-types">';
    foreach ( $post_types  as $post_type ) {
        echo '<option value="'. $post_type.'">' . $post_type . '</option>';
        } 
        echo '</section>';
?>

I understand how users could use their functions.php to hook in their custom post types, but I am trying to avoid that pain for them and rather have the plugin grab all theirs automatically. I've tried looking at other plugins and searching but the search results aren't relevant for this and other plugins were over my head for figuring out.

Appreciate any help, thanks.

1 Answer 1

3

By passing the _builtin argument to get_post_types(), only WordPress default post types will be returned.

Instead, just pass public as an arguement,

Here's an example of output on a development site with WooCommerce activated:

var_dump(get_post_types(['public' => true]));

//result
array(4) {
  ["post"]=>
  string(4) "post"
  ["page"]=>
  string(4) "page"
  ["attachment"]=>
  string(10) "attachment"
  ["product"]=>
  string(7) "product"
}

With no arguments (non-public post types are returned along with public):

var_dump(get_post_types());

//result
array(11) {
  ["post"]=>
  string(4) "post"
  ["page"]=>
  string(4) "page"
  ["attachment"]=>
  string(10) "attachment"
  ["revision"]=>
  string(8) "revision"
  ["nav_menu_item"]=>
  string(13) "nav_menu_item"
  ["product"]=>
  string(7) "product"
  ["product_variation"]=>
  string(17) "product_variation"
  ["shop_order"]=>
  string(10) "shop_order"
  ["shop_order_refund"]=>
  string(17) "shop_order_refund"
  ["shop_coupon"]=>
  string(11) "shop_coupon"
  ["shop_webhook"]=>
  string(12) "shop_webhook"
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.