How to detect if PHP is running inside Widget?

4 replies
Hi Guys

I know by default that WP does not process shortcodes in widgets but there are ways around that restriction.

So ...

My plugin uses a shortcode and I want to prevent it from running if the shortcode is placed in a widget. I need a bit of PHP that will detect if the shortcode is placed within a widget.

Can anyone help?

Thanks in advance.

Will
#detect #php #running #side #widget
  • Profile picture of the author neutralhatter
    since a widget is client side and php is server side, this won't won't work.

    you'll have some abilities with javascript though.

    first thing I would do is recreate the situation by trying to put your page in a widget and detect what browser it renders. I assume it will be the default browser;

    If this is the case, the only option you have is to not-show your page if the window size is smaller then a certain dimension.

    regards,
    {{ DiscussionBoard.errors[8730608].message }}
  • Profile picture of the author 723Media
    The best way to do this is to hook into the widget_text filter:

    add_filter('widget_text', 'your_function_here');

    In your function, you'll need to do some regex to check for shortcode patterns. You can start by checking out this link:

    Function Reference/get shortcode regex « WordPress Codex
    {{ DiscussionBoard.errors[8731585].message }}
  • Profile picture of the author SteveJohnson
    It might be simplest just to de-register any existing shortcode handlers, ouput your widget, then restore the handlers.

    See WordPress Code: Earlier Shortcodes | Viper007Bond.com for some details on how that's done.

    I use the same basic technique for some rather complicated nested shortcodes.
    Signature

    The 2nd Amendment, 1789 - The Original Homeland Security.

    Gun control means never having to say, "I missed you."

    {{ DiscussionBoard.errors[8731748].message }}
  • Profile picture of the author Will Edwards
    Thanks for the replies - appreciated. Bear with me guys. PHP is not my strong suite ...

    @neutralhatter - I appreciate PHP is server side. The shortcode does not trigger a new browser instance; it runs within the widget.

    I have been trying to find PHP code that checks the width of the screen; not browser width but - forgive me if I use the wrong word -container width (widget or post/page) as I also think this might be the easiest way, but I can't find a command that would do that check.

    @723Media - I was working with the code on that page for a while. I thought it might be the answer, but I think the test may be true when the shortcode is used i.e. whether or not it is within a widget. Anyway, could not get it to work.

    @Steve - not sure how this tests whether or not the code is running inside a wodget.

    Thanks again for your help.

    Will
    {{ DiscussionBoard.errors[8732088].message }}

Trending Topics