plugin-icon

Widget Logic

Widget Logic te permite controlar en qué páginas aparecen los widgets usando las etiquetas condicionales de WP's
Valoraciones
4.4
Versión
6.0.9
Instalaciones activas
100K
Última actualización
Jan 15, 2026
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.

La configuración y las opciones se encuentran en la interfaz de administración de widgets habitual.

GRAN ACTUALIZACIÓN:

  • Ahora puedes controlar el widget tanto en el editor de widgets de Gutenberg como en el editor clásico. Es tan fácil como antes, pero también en la vista de Gutenberg.

  • Pre-installed widgets let you add special widget with one click of the mouse. First pre-installed widget is Live Match that let you add widget of one random live football game with real time score updates (teams logos, livescore, minute of the match, tournament name). And more interesting widgets to come!

NOTE ON DEFAULT FUNCTIONS: Widget Logic includes a whitelist of common WordPress conditional tags and safe functions. If you need additional WordPress functions that are not currently whitelisted, please create a topic in our support forum to request them. We regularly add commonly requested functions in new releases.

Configuración

Aside from logic against your widgets, there are three options added to the foot of the widget admin page (see screenshots).

  • 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)

    Puede que necesite retrasar la carga si su lógica depende de funciones definidas, por ejemplo, en el archivo functions.php del tema. Por el contrario, es posible que desee la carga temprana para que el recuento de widgets se calcula correctamente, por ejemplo, para mostrar un diseño alternativo o contenido cuando una barra lateral no tiene 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.

  • Custom PHP Functions — From v.6.0.6 you can use the widget_logic_allowed_functions filter to add custom PHP functions that will be allowed in Widget Logic fields. By default, only WordPress conditional tags and a whitelist of safe functions are available. This filter allows you to extend the functionality and use your own custom functions.

    To add a custom function, add the following code to your theme’s functions.php file:

    `add_filter('widget_logic_allowed_functions', 'my_allowed_functions');

    function my_allowed_functions($functions) { $functions[] = ‘my_custom_function_name‘; return $functions; }`

    You can add multiple functions by using one wrapper function:

    `add_filter('widget_logic_allowed_functions', 'my_allowed_functions');

    function my_allowed_functions($functions) { $functions[] = ‘is_special_page’; $functions[] = ‘is_user_verified’; $functions[] = ‘get_sidebar_title’; return $functions; }`

    IMPORTANT NOTE ON VARIABLES: Widget Logic is designed to work with simple data types (strings, numbers, booleans). If you need to use complex variables, global state, or conditional logic that depends on many factors, create a custom function in your theme’s functions.php file and call it from Widget Logic:

    Good approach (in functions.php):

    `function is_special_page() { global $post; $special_ids = array(5, 10, 15); $conditions = some_complex_function(); return is_page() && in_array($post->ID, $special_ids) && $conditions;

    }`

    Then in Widget Logic field, simply use: is_special_page()

    Less ideal approach (in Widget Logic field): Avoid putting complex logic directly in the Widget Logic field. Keep it simple and let your custom function handle the complexity. This keeps your widget settings clean and maintainable.

Interacción con los servicios externos

Widget Logic utiliza el servicio externo para obtener información actualizada sobre los resultados de los partidos de fútbol. widgetlogic.org es una fuente de información deportiva, que proporciona una amplia gama de información sobre fútbol, incluyendo diversas ligas, torneos y campeonatos de todo el mundo.

El funcionamiento del servicio widgetlogic.org se basa en ofrecer datos en tiempo real acerca de los partidos seleccionados sin necesidad de actualizar la página. Esto significa que los datos se actualizan automáticamente sin necesidad de recargar la página. Este enfoque garantiza a los usuarios un acceso rápido e ininterrumpido a los últimos datos deportivos sin el esfuerzo de actualizar manualmente la información, lo que les permite mantenerse informados sobre los acontecimientos en curso en tiempo real.

Writing Logic Code

El texto del campo «Widget logic» puede ser código PHP completo y debe devolver «verdadero» cuando necesites que aparezca el widget. Si no hay ningún «retorno» en el texto, se añade un «retorno» implícito al principio y un «;» al final. (Esto es sólo para hacer más convenientes las sentencias simples como is_home()).

Los básicos

Haz un buen uso de WP’s own conditional tags. Puede variar y combinar el código utilizando:

  • ! (NO) para invertir la lógica, eg !is_home() es VERDADERO cuando NO es la página de inicio.
  • || (O) para combinar condiciones. X ó Y es VERDADERO cuando X es verdadero o Y es verdadero.
  • && (Y) para crear condiciones más específicas. X y Y es VERDADERO cuando X es verdadero o Y es verdadero.

Hay un montón de buenos ejemplos de código en los foros de WP, y en sitios de WP en toda la red. Pero el Codex WP también está lleno de buenos ejemplos para adaptar, tales como Comprueba si la entrada está en una categoría descendente.

Ejemplos

  • is_home() — sólo la página principal del blog
  • !is_page('about') — en todas partes EXCEPTO en esta «página» específica de WP
  • !is_user_logged_in() — se muestra cuando un usuario no ha iniciado sesión
  • is_category(array(5,9,10,11)) — página de categoría de uno de los ID de categoría dados
  • is_single() && in_category('baked-goods') — un solo mensaje que está en la categoría con este slug
  • current_user_can('level_10') — widget sólo para administradores
  • strpos($_SERVER['HTTP_REFERER'], "google.com")!=false — widget para mostrar cuando se hace clic a través de una búsqueda en Google
  • is_category() && custom_function_to_check_the_category() — category page that’s a descendent of category 5
  • custom_function_from_functions_php_to_check_the_page() — WP page that is a child of page 77
  • custom_function_from_functions_php_to_check_the_page_child_of(13) — home page OR the page that’s a child of page 13
Gratiscon el plan Business
Probado hasta
WordPress 6.9.1
Te puedes descargar este plugin para utilizarlo en tu sitio de .