CanVas
@CanVas
Веб-мастер

Как в wordpress вывести виджет?

Суть проблемы:
В классической функции добавления сайдбара:
register_sidebar( array(
		'name' => __( 'First Footer Widget Area', 'ykushev' ),
		'id'            => 'first-footer-widget-area',
		'description' => __( 'An optional widget area for your site footer.', 'ykushev' ), 
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h4 class="widget-title">',
		'after_title'   => '</h4>',
	) );

мне очень не хватает двух параметров - before_content и after_content.
Точнее мне надо его обернуть в див. И вообще сделать условие на наличие заголовка (title)
Копнув в сторону функции я нашёл код который определяет функцию вывода "dynamic_sidebar( 'primary-widget-area' )"
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/widgets.php */
		do_action( 'dynamic_sidebar_before', $index, false );
		/** This action is documented in wp-includes/widgets.php */
		do_action( 'dynamic_sidebar_after',  $index, false );
		/** This filter is documented in wp-includes/widgets.php */
		return apply_filters( 'dynamic_sidebar_has_widgets', false, $index );
	}

	/**
	 * 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 );
	$sidebar = $wp_registered_sidebars[$index];

	$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'], $id, $classname_);

		/**
		 * Filter 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_id {
		 *     An associative array of widget arguments.
		 *
		 *     @type string $name                Name of the widget.
		 *     @type string $id                  Widget ID.
		 *     @type array|callback $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;
		}
	}

	/**
	 * 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 );

	/**
	 * Filter 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.
	 */

	$did_one = apply_filters( 'dynamic_sidebar_has_widgets', $did_one, $index );

	return $did_one;
}


Поизучав код я полян что весь вывод происходит в строке "do_action( 'dynamic_sidebar_after', $index, true );"
Что не дало мне никаких результатов.
Пробовал выводить var_dump'ом "$wp_registered_widgets" - там только настройки. Никакого html заголовка или тела нет и в помине...
Так как сделать вывод? Или может есть какой плагин?

вот такой код необходимо реализовать:
<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Widget title</h3>
  </div>
  <div class="panel-body">
    Widget content
  </div>
</div>
  • Вопрос задан
  • 1776 просмотров
Пригласить эксперта
Ответы на вопрос 1
wppanda5
@wppanda5 Куратор тега WordPress
WordPress Mедведь
Задача достаточно тривиальная, в register_sidebar() вы передаете массив, добавить в него еще параметров не проблема как и в любой массив, другое дело как вы будете их получать, как минимум придется делать extends Class для каждого необходимого в выводу стандартного виджета.

Однако виджеты обычно устроены так
$before_widget . 
$before_title . 
$title .
$after_title .
$content .
$after_widget;


Соответственно вам достаточно сделать так
register_sidebar( array(
    'name' => __( 'First Footer Widget Area', 'ykushev' ),
    'id'            => 'first-footer-widget-area',
    'description' => __( 'An optional widget area for your site footer.', 'ykushev' ), 
    'before_widget' => '<div id="%1$s" class="widget %2$s">',
    'after_widget'  => '</ЧЕГОТО ПОСЛЕ КОНТЕНТА></div>',
    'before_title'  => '<h4 class="widget-title">',
    'after_title'   => '</h4><ЧЕГОТО ДО КОНТЕНТА>',
  ) );

вернет

$before_widget .
$before_title . 
$title . 
$after_title .
<ЧЕГОТО ДО КОНТЕНТА> .
$content .
</ЧЕГОТО ПОСЛЕ КОНТЕНТА> .
$after_widget;


ну или jquery молоток
$('.widget').append('<ЧЕГОТО ДО КОНТЕНТА></ЧЕГОТО ПОСЛЕ КОНТЕНТА>');
$(".widget header").next().appendTo("ЧЕГОТО ДО КОНТЕНТА");
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы