strange issue with get_post_type() when using it in a shortcode in wordpress text widget

24 Views Asked by At

I have a simple shortcode to show post_type slug when I needed.

when using shortcode in text widget:

-in "post_type single page" it's working

-But in same sidebar and same widget in "post_type archive page" returns nothing.

the strange thing is the same shortcode is working when using do_shortcode function even in the "post_type archive page" template but in text widget has no success.

function post_type_slug()
{
    $string = get_post_type();

    return $string;
}
add_shortcode('pts', 'post_type_slug');
1

There are 1 best solutions below

0
Mohammad J On

unfortunately I have no success with get_post_type() but get_queried_object() helped.

I changed the code to:

function post_type_slug()
{
    $post_type = get_queried_object();
    $post_type = $post_type->rewrite['slug'];

    return $post_type;
}
add_shortcode('pts', 'post_type_slug');

and it's working in text widget now.