<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
* Main class file for the Widget Visibility module.
* @package automattic/jetpack
use Automattic\Block_Scanner;
use Automattic\Jetpack\Assets;
if ( ! defined( 'ABSPATH' ) ) {
* Hide or show legacy widgets conditionally.
* This class has two responsiblities - administrating the conditions in which legacy widgets may be hidden or shown
* and hiding/showing the legacy widgets on the front-end of the site, depending upon the evaluation of those conditions.
* Administrating the conditions can be done in one of four different WordPress screens, plus direct use of the API and
* is supplemented with a legacy widget preview screen. The four different admin screens are
* Gutenberg widget experience - widget admin (widgets.php + API + legacy widget preview)
* Gutenberg widget experience - Customizer (customizer screen/API + API + legacy widget preview)
* Classic widget experience - widget admin (widgets.php + admin-ajax XHR requests)
* Classic widget experience - Customizer (customizer screen/API)
* An introduction to the API endpoints can be found here: https://make.wordpress.org/core/2021/06/29/rest-api-changes-in-wordpress-5-8/
class Jetpack_Widget_Conditions {
* Stores condition for template_redirect action.
public static $passed_template_redirect = false;
public static function init() {
// The Gutenberg based widget experience will show a preview of legacy widgets by including a URL beginning
// widgets.php?legacy-widget-preview inside an iframe. Previews don't need widget editing loaded and also don't
// want to run the filter - if the widget is filtered out it'll be empty, which would be confusing.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['legacy-widget-preview'] ) ) {
// If action is posted and it's save-widget then it's relevant to widget conditions, otherwise it's something
// else and it's not worth registering hooks.
// phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( isset( $_POST['action'] ) && ! isset( $_POST['customize_changeset_uuid'] ) && ! in_array( $_POST['action'], array( 'save-widget', 'update-widget' ), true ) ) {
// API call to *list* the widget types doesn't use editing visibility or display widgets.
if ( isset( $_SERVER['REQUEST_URI'] ) && str_contains( $_SERVER['REQUEST_URI'], '/widget-types?' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$add_data_assets_to_page = false;
$add_html_to_form = false;
$handle_widget_updates = false;
$add_block_controls = false;
// Check to see if using the customizer, but not using the preview. The preview should filter out widgets,
// the customizer controls in the sidebar should not (so they can be edited).
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$customizer_not_previewer = is_customize_preview() && ! isset( $_GET['customize_changeset_uuid'] );
$using_classic_experience = ! wp_use_widgets_block_editor();
if ( $using_classic_experience &&
( $customizer_not_previewer || 'widgets.php' === $pagenow ||
// phpcs:ignore WordPress.Security.NonceVerification.Missing
( 'admin-ajax.php' === $pagenow && array_key_exists( 'action', $_POST ) && 'save-widget' === $_POST['action'] )
$add_data_assets_to_page = true;
$add_html_to_form = true;
$handle_widget_updates = true;
// On a screen that is hosting the API in the gutenberg editing experience.
if ( $customizer_not_previewer || 'widgets.php' === $pagenow ) {
$add_data_assets_to_page = true;
$add_block_controls = true;
// Encoding for a particular widget end point.
if ( isset( $_SERVER['REQUEST_URI'] ) && 1 === preg_match( '|/widget-types/.*/encode|', $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$add_html_to_form = true;
$handle_widget_updates = true;
// Batch API is usually saving but could be anything.
$current_url = ! empty( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
if ( str_contains( $current_url, '/wp-json/batch/v1' ) || 1 === preg_match( '/^\/wp\/v2\/sites\/\d+\/batch\/v1/', $current_url ) ) {
$handle_widget_updates = true;
$add_html_to_form = true;
// Saving widgets via non-batch API. This isn't used within WordPress but could be used by third parties in theory.
if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'GET' !== $_SERVER['REQUEST_METHOD'] && str_contains( $_SERVER['REQUEST_URI'], '/wp/v2/widgets' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$handle_widget_updates = true;
$add_html_to_form = true;
if ( $add_html_to_form ) {
add_action( 'in_widget_form', array( __CLASS__, 'widget_conditions_admin' ), 10, 3 );
if ( $handle_widget_updates ) {
add_filter( 'widget_update_callback', array( __CLASS__, 'widget_update' ), 10, 3 );
if ( $add_data_assets_to_page ) {
add_action( 'sidebar_admin_setup', array( __CLASS__, 'widget_admin_setup' ) );
if ( $add_block_controls ) {
add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'setup_block_controls' ) );
if ( ! $add_html_to_form && ! $handle_widget_updates && ! $add_data_assets_to_page &&
! in_array( $pagenow, array( 'wp-login.php', 'wp-register.php' ), true )
// Not hit any known widget admin endpoint, register widget display hooks instead.
add_filter( 'widget_display_callback', array( __CLASS__, 'filter_widget' ) );
add_filter( 'sidebars_widgets', array( __CLASS__, 'sidebars_widgets' ) );
add_action( 'template_redirect', array( __CLASS__, 'template_redirect' ) );
* Enqueue the block-based widget visibility scripts.
public static function setup_block_controls() {
'widget-visibility-editor',
'_inc/build/widget-visibility/editor/index.js',
'textdomain' => 'jetpack',
Assets::enqueue_script( 'widget-visibility-editor' );
* Add the 'conditions' attribute, where visibility rules are stored, to some blocks.
* We normally add the block attributes in the browser's javascript env only,
* but these blocks use a ServerSideRender dynamic preview, so the php env needs
* to know about the new attribute, too.
public static function add_block_attributes_filter() {
// These use <ServerSideRender>.
'woocommerce/product-categories',
* Filters the list of widget visibility blocks using <ServerSideRender>.
* @module widget-visibility
* @param string[] $blocks Array of block names from WordPress core and WooCommerce.
$blocks_to_add_visibility_conditions = apply_filters( 'jetpack_widget_visibility_server_side_render_blocks', $blocks );
* Block registration filter callback.
* @param array $settings Array of arguments for registering a block type.
* @param string $name Block type name including namespace.
$filter_metadata_registration = function ( $settings, $name ) use ( $blocks_to_add_visibility_conditions ) {
if ( in_array( $name, $blocks_to_add_visibility_conditions, true ) && ! empty( $settings['attributes'] ) ) {
$settings['attributes']['conditions'] = array(
add_filter( 'register_block_type_args', $filter_metadata_registration, 10, 2 );
* Prepare the interface for editing widgets - loading css, javascript & data
public static function widget_admin_setup() {
wp_enqueue_style( 'widget-conditions', plugins_url( 'widget-conditions/widget-conditions.css', __FILE__ ), array( 'widgets' ), JETPACK__VERSION );
wp_style_add_data( 'widget-conditions', 'rtl', 'replace' );
Assets::get_file_url_for_environment(
'_inc/build/widget-visibility/widget-conditions/widget-conditions.min.js',
'modules/widget-visibility/widget-conditions/widget-conditions.js'
array( 'jquery', 'jquery-ui-core' ),
// Set up a single copy of all of the data that Widget Visibility needs.
// This allows all widget conditions to reuse the same data, keeping page size down
// and eliminating the AJAX calls we used to have to use to fetch the minor rule options.
$widget_conditions_data = array();
$widget_conditions_data['category'] = array();
$widget_conditions_data['category'][] = array( '', __( 'All category pages', 'jetpack' ) );
$categories = get_categories(
* Specific a maximum number of categories to query for the Widget visibility UI.
* @module widget-visibility
* @param int $number Maximum number of categories displayed in the Widget visibility UI.
'number' => (int) apply_filters( 'jetpack_widget_visibility_max_number_categories', 1000 ),
usort( $categories, array( __CLASS__, 'strcasecmp_name' ) );
foreach ( $categories as $category ) {
$widget_conditions_data['category'][] = array( (string) $category->term_id, $category->name );
$widget_conditions_data['loggedin'] = array();
$widget_conditions_data['loggedin'][] = array( 'loggedin', __( 'Logged In', 'jetpack' ) );
$widget_conditions_data['loggedin'][] = array( 'loggedout', __( 'Logged Out', 'jetpack' ) );
$widget_conditions_data['author'] = array();
$widget_conditions_data['author'][] = array( '', __( 'All author pages', 'jetpack' ) );
* Query for users with publish caps.
'capability' => array( 'edit_posts' ),
'fields' => array( 'ID', 'display_name' ),
$authors = get_users( $authors_args );
foreach ( $authors as $author ) {
$widget_conditions_data['author'][] = array( (string) $author->ID, $author->display_name );
$widget_conditions_data['role'] = array();
foreach ( $wp_roles->roles as $role_key => $role ) {
$widget_conditions_data['role'][] = array( (string) $role_key, $role['name'] );
$widget_conditions_data['tag'] = array();
$widget_conditions_data['tag'][] = array( '', __( 'All tag pages', 'jetpack' ) );
* Specific a maximum number of tags to query for the Widget visibility UI.
* @module widget-visibility
* @param int $number Maximum number of tags displayed in the Widget visibility UI.
'number' => (int) apply_filters( 'jetpack_widget_visibility_max_number_tags', 1000 ),
usort( $tags, array( __CLASS__, 'strcasecmp_name' ) );
foreach ( $tags as $tag ) {
$widget_conditions_data['tag'][] = array( (string) $tag->term_id, $tag->name );
$widget_conditions_data['date'] = array();
$widget_conditions_data['date'][] = array( '', __( 'All date archives', 'jetpack' ) );
$widget_conditions_data['date'][] = array( 'day', __( 'Daily archives', 'jetpack' ) );
$widget_conditions_data['date'][] = array( 'month', __( 'Monthly archives', 'jetpack' ) );
$widget_conditions_data['date'][] = array( 'year', __( 'Yearly archives', 'jetpack' ) );
$widget_conditions_data['page'] = array();
$widget_conditions_data['page'][] = array( 'front', __( 'Front page', 'jetpack' ) );
$widget_conditions_data['page'][] = array( 'posts', __( 'Posts page', 'jetpack' ) );
$widget_conditions_data['page'][] = array( 'archive', __( 'Archive page', 'jetpack' ) );
$widget_conditions_data['page'][] = array( '404', __( '404 error page', 'jetpack' ) );
$widget_conditions_data['page'][] = array( 'search', __( 'Search results', 'jetpack' ) );
$post_types = get_post_types( array( 'public' => true ), 'objects' );
$widget_conditions_post_types = array();
$widget_conditions_post_type_archives = array();
foreach ( $post_types as $post_type ) {
$widget_conditions_post_types[] = array( 'post_type-' . $post_type->name, $post_type->labels->singular_name );
$widget_conditions_post_type_archives[] = array( 'post_type_archive-' . $post_type->name, $post_type->labels->name );
$widget_conditions_data['page'][] = array( __( 'Post type:', 'jetpack' ), $widget_conditions_post_types );
$widget_conditions_data['page'][] = array( __( 'Post type Archives:', 'jetpack' ), $widget_conditions_post_type_archives );
$pages = self::get_pages();
$dropdown_tree_args = array(
'show_option_none' => '',
'show_option_no_change' => '',
'option_none_value' => '',
$pages_dropdown = walk_page_dropdown_tree( $pages, 0, $dropdown_tree_args );
preg_match_all( '/value=.([0-9]+).[^>]*>([^<]+)</', $pages_dropdown, $page_ids_and_titles, PREG_SET_ORDER );
foreach ( $page_ids_and_titles as $page_id_and_title ) {
$static_pages[] = array( (string) $page_id_and_title[1], $page_id_and_title[2] );
$widget_conditions_data['page'][] = array( __( 'Static page:', 'jetpack' ), $static_pages );
$widget_conditions_data['taxonomy'] = array();
$widget_conditions_data['taxonomy'][] = array( '', __( 'All taxonomy pages', 'jetpack' ) );
$taxonomies = get_taxonomies(
* Filters args passed to get_taxonomies.
* @see https://developer.wordpress.org/reference/functions/get_taxonomies/
* @module widget-visibility
* @param array $args Widget Visibility taxonomy arguments.
apply_filters( 'jetpack_widget_visibility_tax_args', array( '_builtin' => false ) ),
usort( $taxonomies, array( __CLASS__, 'strcasecmp_name' ) );
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_terms = get_terms(
array( $taxonomy->name ),
$widget_conditions_terms = array();
$widget_conditions_terms[] = array( $taxonomy->name, $taxonomy->labels->all_items );
foreach ( $taxonomy_terms as $term ) {
$widget_conditions_terms[] = array( $taxonomy->name . '_tax_' . $term->term_id, $term->name );
$widget_conditions_data['taxonomy'][] = array( $taxonomy->labels->name . ':', $widget_conditions_terms );
wp_localize_script( 'widget-conditions', 'widget_conditions_data', $widget_conditions_data );
// Save a list of the IDs of all pages that have children for dynamically showing the "Include children" checkbox.
$all_pages = self::get_pages();
foreach ( $all_pages as $page ) {
if ( $page->post_parent ) {
$all_parents[ (string) $page->post_parent ] = true;
$front_page_id = get_option( 'page_on_front' );
if ( isset( $all_parents[ $front_page_id ] ) ) {
$all_parents['front'] = true;
wp_localize_script( 'widget-conditions', 'widget_conditions_parent_pages', $all_parents );
* Retrieves a full list of all pages, containing just the IDs, post_parent, post_title, and post_status fields.
* Since the WordPress' `get_pages` function does not allow us to fetch only the fields mentioned
* above, we need to introduce a custom method using a direct SQL query fetching those.
* By fetching only those four fields and not populating the object cache for all the pages, we can
* improve the performance of the query on sites having a lot of pages.
* @see https://core.trac.wordpress.org/ticket/51469
* @return array List of all pages on the site (stdClass objects containing ID, post_title, post_parent, and post_status only).
public static function get_pages() {
$last_changed = wp_cache_get_last_changed( 'posts' );
$cache_key = "get_pages:$last_changed";
$pages = wp_cache_get( $cache_key, 'widget_conditions' );
if ( false === $pages ) {
$pages = $wpdb->get_results( "SELECT {$wpdb->posts}.ID, {$wpdb->posts}.post_parent, {$wpdb->posts}.post_title, {$wpdb->posts}.post_status FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_type = 'page' AND {$wpdb->posts}.post_status = 'publish' ORDER BY {$wpdb->posts}.post_title ASC" );
wp_cache_set( $cache_key, $pages, 'widget_conditions' );
// Copy-pasted from the get_pages function. For usage in the `widget_conditions_get_pages` filter.
'sort_column' => 'post_title',
'exclude_tree' => array(),
'post_status' => 'publish',
* Filters the retrieved list of pages.
* @module widget-visibility
* @param stdClass[] $pages Array of objects containing only the ID, post_parent, post_title, and post_status fields.
* @param array $parsed_args Array of get_pages() arguments.
return apply_filters( 'jetpack_widget_visibility_get_pages', $pages, $parsed_args );
* Add the widget conditions to each widget in the admin.
* @param WP_Widget $widget Widget to add conditions settings to.
* @param null $return unused.
* @param array $instance The widget settings.
public static function widget_conditions_admin( $widget, $return, $instance ) {
if ( isset( $instance['conditions'] ) ) {
$conditions = $instance['conditions'];
if ( ! isset( $conditions['action'] ) ) {
$conditions['action'] = 'show';
if ( empty( $conditions['rules'] ) ) {
$conditions['rules'][] = array(
if ( empty( $conditions['match_all'] ) ) {
$conditions['match_all'] = false;