WordPress как на ладони
Очень Удобный и Быстрый Хостинг для сайтов на WordPress. Пользуюсь сам и вам рекомендую!

dynamic_sidebar()WP 2.2.0

Выводит на экран первую активную панель виджетов (сайдбар - панель в которой есть хотя бы один виджет). Можно указать ID или номер панели, какую именно выводить, если на сайте большее одной панели виджетов.

dynamic_sidebar() возвращает true или false, с возвращаемым результатом, также выводит на экран панель виджетов. Возвращаемое значение можно использовать, например, чтобы определить нужно ли обрабатывать код заменяющий виджеты, когда в панели нет виджетов (см. пример #1).

Если при регистрации панели виджетов с помощью функции register_sidebar(), в качестве аргумента id вы использовали число, то в dynamic_sidebar() указывайте это число. Если вы использовали название (строку), то указывайте его. Подробнее смотрите ниже, в пункте Множественные сайдбары.

Возвращает

true|false. true, если панель с виджетами была найдена. false, если панели нет, или в ней нет виджетов.

Использование

<ul id="sidebar">
	<?php dynamic_sidebar( $index ); ?>
</ul>
$index(строка/число)
Идентификатор панели, указанный в параметре id функции register_sidebar(), при регистрации панели. Если указано число, то будет искаться панель с ID sidebar-$index.
По умолчанию: 1 (sidebar-1)

Примеры

2

#1 Выводим нужный сайдбар.

<ul id="sidebar">
	<?php dynamic_sidebar( 'right-sidebar' ); ?>
</ul>
2

#2 Проверяем наличие панели и выводим её

В примере 2 мы не проверяли наличие панели и виджетов в ней. В этом примере мы проверим наличие панели, чтобы не выводить лишние HTML теги (<ul id="sidebar">), если сайдбар пустой:

<?php if ( is_active_sidebar( 'left-sidebar' ) ) : ?>
	<ul id="sidebar">
		<?php dynamic_sidebar( 'left-sidebar' ); ?>
	</ul>
<?php endif; ?>
2

#3 Множественные сайдбары

При регистрации более одной панели виджетов с помощью register_sidebar() удобнее указывать id для каждой панели.

Мы можем не указывать id, тогда панель получит порядковый номер. Но в этом случае, при редактировании темы сложно будет понять какая панель какая, ведь числа 1, 2, 3 ни о чем не говорят. Но если задать название, становится гораздо понятнее:

// --- числа
// регистрация
register_sidebar();
// вывод
dynamic_sidebar(1);

// --- Строки
// регистрация
register_sidebar( array( 'id' => 'top_menu') );
// вывод
dynamic_sidebar( 'top_menu' );

Из примера, видно, что со строками удобнее: заглянув в тему и увидев dynamic_sidebar( 'top_menu' ) сразу понятно, что вызывается панель для главного меню.

Аргумент id не должен содержать пробелов, заглавных букв, кириллических букв. В нем можно использовать тире - и подчеркивание _. Также он должен быть уникальным. Указывая id мы также можем указать название, описание и переводы для них:

register_sidebar( array(
	'id'          => 'top-menu',
	'name'        => __( 'Top Menu', $text_domain ),
	'description' => __( 'This sidebar is located above the age logo.', $text_domain ),
) );
1

#4 Выводим сайдбар, если он есть.

Этот пример показывает как вывести первый не пустой сайдбар (при регистрации id сайдара не был указан) или если он не найден обработать указанный код:

<ul id="sidebar">
<?php if ( ! dynamic_sidebar() ) : ?>
	<li><!-- код блока 1 --></li>
	<li><!-- код блока 2 --></li>
<?php endif; ?>
</ul>

Заметки

  • Global. Массив. $wp_registered_sidebars The registered sidebars.
  • Global. Массив. $wp_registered_widgets The registered widgets.

Список изменений

С версии 2.2.0 Введена.

Код dynamic_sidebar() WP 6.5.2

function dynamic_sidebar( $index = 1 ) {
	global $wp_registered_sidebars, $wp_registered_widgets;

	if ( is_int( $index ) ) {
		$index = "sidebar-$index";
	} else {
		$index = sanitize_title( $index );
		foreach ( (array) $wp_registered_sidebars as $key => $value ) {
			if ( sanitize_title( $value['name'] ) === $index ) {
				$index = $key;
				break;
			}
		}
	}

	$sidebars_widgets = wp_get_sidebars_widgets();
	if ( empty( $wp_registered_sidebars[ $index ] ) || empty( $sidebars_widgets[ $index ] ) || ! is_array( $sidebars_widgets[ $index ] ) ) {
		/** This action is documented in wp-includes/widget.php */
		do_action( 'dynamic_sidebar_before', $index, false );
		/** This action is documented in wp-includes/widget.php */
		do_action( 'dynamic_sidebar_after', $index, false );
		/** This filter is documented in wp-includes/widget.php */
		return apply_filters( 'dynamic_sidebar_has_widgets', false, $index );
	}

	$sidebar = $wp_registered_sidebars[ $index ];

	$sidebar['before_sidebar'] = sprintf( $sidebar['before_sidebar'], $sidebar['id'], $sidebar['class'] );

	/**
	 * Fires before widgets are rendered in a dynamic sidebar.
	 *
	 * Note: The action also fires for empty sidebars, and on both the front end
	 * and back end, including the Inactive Widgets sidebar on the Widgets screen.
	 *
	 * @since 3.9.0
	 *
	 * @param int|string $index       Index, name, or ID of the dynamic sidebar.
	 * @param bool       $has_widgets Whether the sidebar is populated with widgets.
	 *                                Default true.
	 */
	do_action( 'dynamic_sidebar_before', $index, true );

	if ( ! is_admin() && ! empty( $sidebar['before_sidebar'] ) ) {
		echo $sidebar['before_sidebar'];
	}

	$did_one = false;
	foreach ( (array) $sidebars_widgets[ $index ] as $id ) {

		if ( ! isset( $wp_registered_widgets[ $id ] ) ) {
			continue;
		}

		$params = array_merge(
			array(
				array_merge(
					$sidebar,
					array(
						'widget_id'   => $id,
						'widget_name' => $wp_registered_widgets[ $id ]['name'],
					)
				),
			),
			(array) $wp_registered_widgets[ $id ]['params']
		);

		// Substitute HTML `id` and `class` attributes into `before_widget`.
		$classname_ = '';
		foreach ( (array) $wp_registered_widgets[ $id ]['classname'] as $cn ) {
			if ( is_string( $cn ) ) {
				$classname_ .= '_' . $cn;
			} elseif ( is_object( $cn ) ) {
				$classname_ .= '_' . get_class( $cn );
			}
		}
		$classname_ = ltrim( $classname_, '_' );

		$params[0]['before_widget'] = sprintf(
			$params[0]['before_widget'],
			str_replace( '\\', '_', $id ),
			$classname_
		);

		/**
		 * Filters the parameters passed to a widget's display callback.
		 *
		 * Note: The filter is evaluated on both the front end and back end,
		 * including for the Inactive Widgets sidebar on the Widgets screen.
		 *
		 * @since 2.5.0
		 *
		 * @see register_sidebar()
		 *
		 * @param array $params {
		 *     @type array $args  {
		 *         An array of widget display arguments.
		 *
		 *         @type string $name          Name of the sidebar the widget is assigned to.
		 *         @type string $id            ID of the sidebar the widget is assigned to.
		 *         @type string $description   The sidebar description.
		 *         @type string $class         CSS class applied to the sidebar container.
		 *         @type string $before_widget HTML markup to prepend to each widget in the sidebar.
		 *         @type string $after_widget  HTML markup to append to each widget in the sidebar.
		 *         @type string $before_title  HTML markup to prepend to the widget title when displayed.
		 *         @type string $after_title   HTML markup to append to the widget title when displayed.
		 *         @type string $widget_id     ID of the widget.
		 *         @type string $widget_name   Name of the widget.
		 *     }
		 *     @type array $widget_args {
		 *         An array of multi-widget arguments.
		 *
		 *         @type int $number Number increment used for multiples of the same widget.
		 *     }
		 * }
		 */
		$params = apply_filters( 'dynamic_sidebar_params', $params );

		$callback = $wp_registered_widgets[ $id ]['callback'];

		/**
		 * Fires before a widget's display callback is called.
		 *
		 * Note: The action fires on both the front end and back end, including
		 * for widgets in the Inactive Widgets sidebar on the Widgets screen.
		 *
		 * The action is not fired for empty sidebars.
		 *
		 * @since 3.0.0
		 *
		 * @param array $widget {
		 *     An associative array of widget arguments.
		 *
		 *     @type string   $name        Name of the widget.
		 *     @type string   $id          Widget ID.
		 *     @type callable $callback    When the hook is fired on the front end, `$callback` is an array
		 *                                 containing the widget object. Fired on the back end, `$callback`
		 *                                 is 'wp_widget_control', see `$_callback`.
		 *     @type array    $params      An associative array of multi-widget arguments.
		 *     @type string   $classname   CSS class applied to the widget container.
		 *     @type string   $description The widget description.
		 *     @type array    $_callback   When the hook is fired on the back end, `$_callback` is populated
		 *                                 with an array containing the widget object, see `$callback`.
		 * }
		 */
		do_action( 'dynamic_sidebar', $wp_registered_widgets[ $id ] );

		if ( is_callable( $callback ) ) {
			call_user_func_array( $callback, $params );
			$did_one = true;
		}
	}

	if ( ! is_admin() && ! empty( $sidebar['after_sidebar'] ) ) {
		echo $sidebar['after_sidebar'];
	}

	/**
	 * Fires after widgets are rendered in a dynamic sidebar.
	 *
	 * Note: The action also fires for empty sidebars, and on both the front end
	 * and back end, including the Inactive Widgets sidebar on the Widgets screen.
	 *
	 * @since 3.9.0
	 *
	 * @param int|string $index       Index, name, or ID of the dynamic sidebar.
	 * @param bool       $has_widgets Whether the sidebar is populated with widgets.
	 *                                Default true.
	 */
	do_action( 'dynamic_sidebar_after', $index, true );

	/**
	 * Filters whether a sidebar has widgets.
	 *
	 * Note: The filter is also evaluated for empty sidebars, and on both the front end
	 * and back end, including the Inactive Widgets sidebar on the Widgets screen.
	 *
	 * @since 3.9.0
	 *
	 * @param bool       $did_one Whether at least one widget was rendered in the sidebar.
	 *                            Default false.
	 * @param int|string $index   Index, name, or ID of the dynamic sidebar.
	 */
	return apply_filters( 'dynamic_sidebar_has_widgets', $did_one, $index );
}
2 комментария
    Войти