Search code examples
phpwordpressvisual-composer

How to get all custom post types in wordpress?


I am trying to make a shortcode for Visual Composer. I have to get all the custom post types as dropdown. I am using the get_post_types() function, but it returns an empty array.

Here is my code:

 /*Post type shortcode*/
 add_action( 'vc_before_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
                    //"holder"        => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label" => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types,
            ),
        )
    ) );

}

I have also tried to get it in the functions.php but result is same.

I also used add_action('init',"function_name');, it works within the hook but not outside of the hook.

Can any one help me please?


Solution

  • Try with admin_init hook, which runs after init:

    /*Post type shortcode*/
    add_action( 'admin_init', 'post_type_shortcode');
    function post_type_shortcode(){
    $args = array( 'public' => true, '_builtin' => false );
    $output = 'names'; //'names'; // names or objects, note names is the default
    $operator = 'and'; // 'and' or 'or'
    $custom_post_types = get_post_types( $args, $output, $operator );
    vc_map( array(
        "name" => __( "Display Post Type", "saue" ),
        "description" => "Display post type",
        "base" => "display_post_type",
        "class" => "",
        "category" => __( "Saue Theme", "saue"),
        "params" => array(
            array(
                "type"          => "dropdown",
                        //"holder"        => "div",
                "heading"       => __( "Post Type", "saue" ),
                "admin_label" => true,
                "param_name"    => "post_type",
                "value"         => $custom_post_types,
                ),
            )
        ) );
    
    }