Cette extension n’a pas été testée avec plus de trois mises à jour majeures de WordPress. Elle peut ne plus être maintenue ou supportée et peut avoir des problèmes de compatibilité lorsqu’elle est utilisée avec des versions de WordPress plus récentes.

Widget Logic


This plugin gives every widget an extra control field called « Widget logic » that lets you control the pages that the widget will appear on. The text field lets you use WP’s Conditional Tags, or any general PHP code.

PLEASE NOTE The widget logic you introduce is EVAL’d directly. Anyone who has access to edit widget appearance will have the right to add any code, including malicious and possibly destructive functions. There is an optional filter ‘widget_logic_eval_override’ which you can use to bypass the EVAL with your own code if needed. (See Other Notes).

The configuring and options are in the usual widget admin interface.


Outre la logique par rapport à vos widgets, trois options sont ajoutées au bas de la page d’administration du widget (voir captures d’écran).

  • Use ‘wp_reset_query’ fix — Many features of WP, as well as the many themes and plugins out there, can mess with the conditional tags, such that is_home is NOT true on the home page. This can often be fixed with a quick wp_reset_query() statement just before the widgets are called, and this option puts that in for you rather than having to resort to code editing

  • Load logic — This option allows you to set the point in the page load at which your widget logic if first checked. Pre v.50 it was when the ‘wp_head’ trigger happened, ie during the creation of the HTML’s HEAD block. Many themes didn’t call wp_head, which was a problem. From v.50 it happens, by default, as early as possible, which is as soon as the plugin loads. You can now specify these ‘late load’ points (in chronological order):

    • after the theme loads (after_setup_theme trigger)
    • when all PHP loaded (wp_loaded trigger)
    • after query variables set (parse_query) – this is the default
    • during page header (wp_head trigger)

    Vous devrez peut-être retarder le chargement si votre logique dépend de fonctions définies, par exemple dans le fichier functions.php du thème. Inversement, vous pouvez souhaiter charger plus tôt pour que le nombre de widgets soit calculé correctement, par exemple pour afficher une présentation ou un contenu alternatif lorsqu’une colonne latérale ne contient aucun widgets.

  • Don’t cache widget logic results — From v .58 the widget logic code should only execute once, but that might cause unexpected results with some themes, so this option is here to turn that behaviour off. (The truth/false of the code will be evaluated every time the sidebars_widgets filter is called.

Writing Logic Code

The text in the ‘Widget logic’ field can be full PHP code and should return ‘true’ when you need the widget to appear. If there is no ‘return’ in the text, an implicit ‘return’ is added to the start and a ‘;’ is added on the end. (This is just to make single statements like is_home() more convenient.)

The Basics

Make good use of WP’s own conditional tags. You can vary and combine code using:

  • ! (NOT) to reverse the logic, eg !is_home() is TRUE when this is NOT the home page.
  • || (OR) to combine conditions. X OR Y is TRUE when either X is true or Y is true.
  • && (AND) to make conditions more specific. X AND Y is TRUE when both X is true and Y is true.

There are lots of great code examples on the WP forums, and on WP sites across the net. But the WP Codex is also full of good examples to adapt, such as Test if post is in a descendent category.


  • is_home() — just the main blog page
  • !is_page('about') — everywhere EXCEPT this specific WP ‘page’
  • !is_user_logged_in() — shown when a user is not logged in
  • is_category(array(5,9,10,11)) — category page of one of the given category IDs
  • is_single() && in_category('baked-goods') — single post that’s in the category with this slug
  • current_user_can('level_10') — admin only widget
  • strpos($_SERVER['HTTP_REFERER'], "google.com")!=false — widget to show when clicked through from a google search
  • is_category() && in_array($cat, get_term_children( 5, 'category')) — category page that’s a descendent of category 5
  • global $post; return (in_array(77,get_post_ancestors($post))); — WP page that is a child of page 77
  • global $post; return (is_page('home') || ($post->post_parent=="13")); — home page OR the page that’s a child of page 13

Note the extra ‘;’ on the end where there is an explicit ‘return’.

Le filtre “widget_logic_eval_override”

Before the Widget Logic code is evaluated for each widget, the text of the Widget Logic code is passed through this filter. If the filter returns a BOOLEAN result, this is used instead to determine if the widget is visible. Return TRUE for visible.

Captures d’écran

  • The ‘Widget logic’ field at work in standard widgets.
  • The plugin options are at the foot of the usual widget admin page… wp_reset_query option, ‘load logic point’ and ‘evaluate more than once’. You can also export and import your site’s WL options as a plain text file for a quick backup/restore and to help troubleshoot issues.


Que puis-je essayer si ça ne marche pas ?
  • Switch to the default theme. If the problem goes away, your theme may be interfering with the WP conditional tags or how widgets work
  • Try the wp_reset_query option. If your theme performs custom queries before calling the dynamic sidebar this might help.
  • Try a different ‘Load logic’ point. Most wordpress conditional tags only work ‘after query variables set’, but some plugins may require evaluation earlier or later.
  • The ‘Evaluate widget logic more than once’ option may be needed if you have to use an early ‘Load logic’ point.
Je reçois des erreurs qui s’affichent comme “erreur PHP Parse…… code de eval () sur la ligne 1”

Vous avez une erreur de syntaxe PHP dans l’un des champs Widget Logic de votre widget. Examinez-les pour les erreurs. Vous trouverez peut-être plus facile de vérifier en utilisant “Options d’exportation” et en lisant le code (notez que les guillemets simples et doubles sont échappés avec plusieurs caractères de barre oblique inversée).

Si vous rencontrez des difficultés pour trouver l’erreur de syntaxe, une méthode de dépannage simple consiste à utiliser les “Options d’exportation” pour conserver une copie, puis à effacer chaque champ de la logique du widget jusqu’à ce que le problème disparaisse. Une fois que vous avez identifié le code problématique, vous pouvez restaurer le reste avec “Options d’importation”.

Cela cause des problèmes avec WooCommerce ou d’autres extensions populaires

C’est souvent, pas toujours, résolu en essayant les différentes options de “logique de chargement”. L’option “après avoir défini les variables de requête” semble être la meilleure solution par défaut, essayez-la.

Qu’est-ce qu’il y a dans ma colonne latérale s’il n’y a aucun widgets ?

Since v .50 the widget logic code runs such that when dynamic_sidebar is called in a theme’s code it will ‘return false’ if no widgets are present. In such cases many themes are coded to put in some default sidebar text in place of widgets, which is what you are seeing.

Your options, if you want this default sidebar content gone, are to either edit the theme, or as a work around, add an empty text widget (no title, no content) to the end of the sidebar’s widget list.

Comment puis-je obtenir le widget X uniquement sur ma page d’accueil ? (Ou sur chaque page sauf xxx.)

There is some confusion between the Main Page and the front page. If you want a widget on your ‘front page’ whether that is a static page or a set of posts, use is_front_page(). If it is a page using is_page(x) does not work. If your ‘front page’ is a page and not a series of posts, you can still use is_home() to get widgets on that main posts page (as defined in Admin > Settings > Reading).

La logique utilisant is_page() ne fonctionne pas

Je crois que ceci est corrigé dans la v5.7.0. Faites-moi savoir si ce n’est pas le cas.

If your theme calls the sidebar after the loop you should find that the wp_reset_query option fixes things. This problem is explained on the is_page codex page.

Comment faire en sorte qu’un widget apparaisse à la fois sur une page de catégorie et sur des publications seules dans cette catégorie ?

Take care with your conditional tags. There is both an in_category and is_category tag. One is used to tell if the ‘current’ post is IN a category, and the other is used to tell if the page showing IS for that category (same goes for tags etc). What you want is the case when:

(this page IS category X) OR (this is a single post AND this post is IN category X)

which in proper PHP is:

is_category(X) || (is_single() && in_category(X))
How do I get a widget to appear when X, Y and Z?

Have a go at it yourself first. Check out the ‘Writing Logic Code’ section under Other Notes.

Why is Widget Logic so unfriendly, you have to be a code demon to use it?

This is sort of deliberate. I originally wrote it to be as flexible as possible with the thought of writing a drag’n’drop UI at some point. I never got round to it, because (I’m lazy and) I couldn’t make it both look nice and let you fall back to ‘pure code’ (for the possibilities harder to cater for in a UI).

The plugin Widget Context presents a nice UI and has a neat ‘URL matching’ function too.

Widgets appear when they shouldn’t

It might be that your theme performs custom queries before calling the sidebar. Try the wp_reset_query option.

Alternatively you may have not defined your logic tightly enough. For example when the sidebar is being processed, in_category(‘cheese’) will be true if the last post on an archive page is in the ‘cheese’ category.

Tighten up your definitions with PHPs ‘logical AND’ &&, for example:

is_single() && in_category('cheese')


17 avril 2020
This plugin is very useful, I recommend it I have been using this plugin for years and it is great.
3 avril 2020 1 réponse
Dzień dobry, Wtyczka jest REWELACYJNA. Prosta bez wielu niezrozumiałych i niepotrzebnych ustawień. Cały dzień szukania i testowania różnych wtyczek. Przy pomocy krótkiego kodu ustawiamy wyświetlanie widgetów na tych stronach, które mają przekazać dodatkowe informacje. Pozdawiam – marekjar
30 juillet 2019
Спасибо за попытку облегчить нам жизнь. К сожалению при скрытии виджета он не исчезает вообще, а становится полупрозрачным. Кроме того, плагин сделан не для обычных людей, очень сложный и не интуитивно понятный.
Lire les 182 avis

Contributeurs/contributrices & développeurs/développeuses

« Widget Logic » est un logiciel libre. Les personnes suivantes ont contribué à cette extension.


“Widget Logic” a été traduit dans 18 locales. Remerciez l’équipe de traduction pour ses contributions.

Traduisez « Widget Logic » dans votre langue.

Le développement vous intéresse ?

Parcourir le code, consulter le SVN dépôt, ou s’inscrire au journal de développement par RSS.



  • Security update. The export feature has been protected with nonce.



  • The plugin’s security has been improved, big thanks to Paul Dannewitz for his excellent security audit!
  • The widget_content filter option has been removed from the settings block, but kept in the code for backward compatibility. The plan is to remove it completely and make the plugin simpler (let us know what you think).
  • Code cleanup.


wp_reset_query works better under certain conditions.


The code has been adapted to work on the servers with restricted <?=

Fixed support for the wp_register_sidebar_widget widgets.

Some content was prepared for translation.


Fixed the issue of displaying errors under certain conditions.


Added full support for WP customizer.

In case of a fatal error in logic, the widget will not be displayed.


Fixed the « Warning: Attempt to assign property of non-object » bug.


Fixed the issue when in some cases the plugin displayed user logic errors in the Widgets section and this didn’t allow to save the widgets.

Fixed ini_set() related warnings for some rare hosting configurations.


Removed conflicts with outdated WP versions.


Fixed the settings form not being saved settings under some circumstances.

Added a setting to show logic code errors for admins (turned off by default).

Fixed the issue with quotes in error messages on some WP installations.


Fixed PHP 7 compatibility issue.

Fixed a conflict with the latest WPML plugin.

A new default load logic point attached to the action ‘parse_query’. By default the widget logic is only evaluated once.

Translation added: Ukrainian by Roman Sulym


Small fixes to satisfy some define(‘WP_DEBUG’, true) errors


Small fix to the original WP3.5 fix in 0.54 that had the side effect of failing to save logic text on newly added widgets.


Restored a striplashes that vanished in 0.54 causing much grief.

Translation: Spanish by Eduardo Larequi https://wordpress.org/support/profile/elarequi


Removed a WP 3.1+ function call, hopefully making it 2.8 compatible again.

A little ‘trim’ of WL code to stop « syntax error, unexpected ‘)’ » errors, which could occur if your WL was just a single space. Thanks to https://twitter.com/chrisjean for pointing this out.

Translation support! Thanks to Foe Services Labs https://wordpress.org/support/profile/cfoellmann for the work on this and the German Social Translation

Added a ‘widget_logic_eval_override’ filter. This allows advanced users to bypass EVAL with a function of their own.


Accidentally released code with a terrible bug in it 🙁


Two new features: optional delayed loading of logic (see Configuration under Installation), and the ability to save out and reload all your site’s widget logic into a config file


One important bug fix (fairly major and fairly stupid of me too)


For the first time since this started on WP 2.3, I’ve rewritten how the core widget logic function works, so there may be ‘bumps ahead’.

It now uses the ‘sidebars_widgets’ filter (as it should have done when that was
introduced in WP2.8 by the look of it). The upshot is that is_active_sidebar should behave properly.

Widget callbacks only get intercepted if the ‘widget_content’ filter is activated, and much more briefly. (A widget’s ‘callback’ is rewired within the ‘dynamic_sidebar’ function just before the widget is called, by the ‘dynamic_sidebar_param’ filter, and is restored when the callback function is invoked.)


Kill some poor coding practices that throws debug notices – thanks to John James Jacoby.


FINALLY tracked down the elusive ‘wp_reset_query’ option resetting bug.


Fix to work with new WP2.8 admin ajax. With bonus fixes.


Officially works with 2.7 now. Documentation changes and minor bug fixes.


simple bug fix (form data was being lost when ‘Cancel’ing widgets)


WP 2.5+ only now. WP’s widget admin has changed so much and I was getting tied up in knots trying to make it work with them both.


Brings WP 2.5 compatibility. I am trying to make it back compatible. If you have trouble using WL with WP 2.1–2.3 let me know the issue. Thanks to Kjetil Flekkoy for reporting and helping to diagnose errors in this version


Last WP 2.3 only version