get_post_types()

最后更新于:2021-11-26 22:45:19

get_post_types( array|string$args=array(), string$output=’names’, string$operator=’and’)

Get a list of all registered post type objects.

参数

$args

(array|string) (Optional) An array of key => value arguments to match against the post type objects.

Default value: array()

$output

(string) (Optional) The type of output to return. Accepts post type ‘names’ or ‘objects’.

Default value: ‘names’

$operator

(string) (Optional) The logical operation to perform. ‘or’ means only one element from the array needs to match; ‘and’ means all elements must match; ‘not’ means no elements may match.

Default value: ‘and’

响应

(string[]|GC_Post_Type[]) An array of post type names or objects.

源文件

文件: gc-includes/post.php

function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
	global $gc_post_types;

	$field = ( 'names' === $output ) ? 'name' : false;

	return gc_filter_object_list( $gc_post_types, $args, $operator, $field );
}
<?php
$args = array(
   'public'   => true,
   '_builtin' => false
);
 
$output = 'names'; // 'names' or 'objects' (default: 'names')
$operator = 'and'; // 'and' or 'or' (default: 'and')
 
$post_types = get_post_types( $args, $output, $operator );
 
if ( $post_types ) { // If there are any custom public post types.
 
    echo '<ul>';
 
    foreach ( $post_types  as $post_type ) {
        echo '<li>' . $post_type . '</li>';
    }
 
    echo '<ul>';
 
}
?>
<?php
// Get post types
$args       = array(
	'public' => true,
);
$post_types = get_post_types( $args, 'objects' );
?>

<select class="widefat" name="post_type">
    <?php foreach ( $post_types as $post_type_obj ):
        $labels = get_post_type_labels( $post_type_obj );
        ?>
        <option value="<?php echo esc_attr( $post_type_obj->name ); ?>"><?php echo esc_html( $labels->name ); ?></option>
    <?php endforeach; ?>
</select>
<?php
$post_types = get_post_types(array('public' => true), 'names', 'and');
?>
<select class="" name="post_type">
  <?php

  foreach ($post_types  as $post_type) {
  ?>
    <option value="<?php echo esc_attr($post_type); ?>"><?php echo esc_html($post_type); ?></option>
  <?php
  }
  ?>
</select>
?>