Function and usage of get_post_types() in wordpress

Question

Answers ( 1 )

    0
    2024-01-07T17:35:27+00:00

    The get_post_types() function in WordPress is a powerful tool for retrieving a list of all registered post type objects. This function is particularly useful when you need to work with different types of content in a WordPress website, such as posts, pages, or custom post types.

    Function:

    • Purpose: To get a list of all registered post type objects.

    Description:

    • This function is closely related to the register_post_type() function, which is used to register new post types in WordPress. The get_post_types() function allows you to retrieve these post types based on certain criteria.

    Parameters:

    1. $args (array|string, optional):

      • This parameter allows you to specify an array of key-value pairs to match against the post type objects.
      • Default Value: An empty array array().
    2. $output (string, optional):

      • This parameter defines the type of output you want to receive.
      • You can specify 'names' to get the names of the post types or 'objects' to get the post type objects.
      • Default Value: 'names'.
    3. $operator (string, optional):

      • This parameter specifies the logical operation to perform on the $args array.
      • Options include 'or' (only one element from the array needs to match), 'and' (all elements must match), and 'not' (no elements may match).
      • Default Value: 'and'.

    Return:

    • Type: string[]|WP_Post_Type[]
    • The function returns an array. The content of this array depends on the $output parameter:
      • If 'names' is specified, you get an array of post type names.
      • If 'objects' is specified, you get an array of post type objects.

    Sample Usage:

    // Example 1: Retrieve names of all registered post types
    $post_types = get_post_types(); 
    foreach ( $post_types as $post_type ) {
       echo $post_type;
    }
    
    // Example 2: Retrieve post type objects with specific attributes
    $args = array(
       'public'   => true,
       'show_ui'  => true
    );
    $output = 'objects'; 
    $operator = 'and'; 
    
    $post_types = get_post_types( $args, $output, $operator ); 
    foreach ( $post_types as $post_type ) {
       print_r( $post_type );
    }
    

    In these examples, the first one retrieves the names of all registered post types, while the second one retrieves post type objects that are both public and have a user interface (UI) in the admin area.

Leave an answer