plugin-icon

Widget Logic

Widget Logic te permite controlar en qué páginas aparecen los widgets usando las etiquetas condicionales de WP's
Valoración
4.4/5
Versión
6.0.6
Instalaciones activas
100K
Última actualización
Jul 17, 2025
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).

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!

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.

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() && in_array($cat, get_term_children( 5, 'category')) — página de categoría descendiente de la categoría 5
  • global $post; return (in_array(77,get_post_ancestors($post))); — Página WP hija de la página 77
  • global $post; return (is_page('home') || ($post->post_parent=="13")); — página de inicio O la página hija de la página 13

Observa el «;» adicional al final, donde hay un «retorno» explícito.

The ‘widget_logic_eval_override’ filter

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.

Gratiscon el plan Business
Probado hasta
WordPress 6.8.3
Te puedes descargar este plugin para utilizarlo en tu sitio de .