- Добавление PHP-кода в виджеты WordPress без использования плагинов
- Миша
- Php function widget wordpress
- This is a text widget
- Developing Widgets
- Your Widget Class
- Registering a Widget
- Examples
- Example Text Widget
- Sample Widget
- Example with a Namespace
- Special considerations
- the_widget() │ WP 2.8.0
- Возвращает
- Использование
Добавление PHP-кода в виджеты WordPress без использования плагинов
По умолчанию виджеты поддерживают только обычный текст и HTML-код. Но люди очень часто сталкиваются с необходимостью вставки в виджет кода PHP, например при установки Sape.
Конечно, есть уйма плагинов, позволяющих это реализовать, но мы, как обычно, воздержимся от их использования и всё, что потребуется — это вставить следующий код в functions.php текущей темы:
function php_in_widgets($widget_content) { if (strpos($widget_content, ' . '?') !== false) { ob_start(); eval('?' . '>' . $widget_content); $widget_content = ob_get_contents(); ob_end_clean(); } return $widget_content; } add_filter('widget_text', 'php_in_widgets', 99);
Та-дам, теперь можете добавлять PHP-код в текстовые виджеты. И никаких плагинов.
Миша
Впервые познакомился с WordPress в 2009 году. Организатор и спикер на конференциях WordCamp. Преподаватель в школе Нетология.
Пишите, если нужна помощь с сайтом или разработка с нуля.
Php function widget wordpress
HTML output for this widget looks like this:
', ); public function widget( $args, $instance ) < echo $args['before_widget']; if ( ! empty( $instance['title'] ) ) < echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title']; >echo 'This is a text widget
I can put HTML in here. Search me!Each widget has its own way of outputting HTML that is relevant to the data being displayed. The wrapper tags for the widget are defined by the widget area in which it is being displayed.
The PHP code necessary to create a widget like the built-in text widget looks like this:
); > public $args = array( 'before_title' => '
', 'after_title' => '
', 'before_widget' => '', 'after_widget' => ''; echo esc_html__( $instance['text'], 'text_domain' ); echo ''; echo $args['after_widget']; > public function form( $instance ) < $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( '', 'text_domain' ); $text = ! empty( $instance['text'] ) ? $instance['text'] : esc_html__( '', 'text_domain' ); ?>get_field_id( 'title' ) ); ?>"> get_field_name( 'title' ) ); ?>" type="text" value="">
get_field_id( 'Text' ) ); ?>"> get_field_name( 'text' ) ); ?>" type="text" cols="30" rows="10">
public function update( $new_instance, $old_instance ) < $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; $instance['text'] = ( ! empty( $new_instance['text'] ) ) ? $new_instance['text'] : ''; return $instance; >> $my_widget = new My_Widget();The code above will be explained in detail later in the article.
Developing Widgets
To create and display a widget, you need to do the following:
- Create your widget’s class by extending the standard WP_Widget class and some of its functions.
- Register your widget so that it’s made available in the Widgets screen.
- Make sure that your theme has at least one widget area in which to add the widgets.
Your Widget Class
public function widget( $args, $instance ) < // outputs the content of the widget >public function form( $instance ) < // outputs the options form in the admin >public function update( $new_instance, $old_instance ) < // processes widget options to be saved >>
The documentation for each of these functions can be found in the widget class code:
- construct : Set up your widget with a description, name, and display width in your admin.
- widget : Process the widget options and display the HTML on your page. The $args parameter provides the HTML you can use to display the widget title class and widget content class.
- form : Display the form that will be used to set the options for your widget. If your widget doesn’t have any options, you can skip this function (although it is still best practice to include it even if it’s empty).
- update : Save the widget options to the database. If your widget doesn’t have any options, you can skip this function (although it is still best practice to include it even if it’s empty).
Registering a Widget
The register_widget() function is used to register a widget.
Call this function using the widgets_init hook:
Examples
Example Text Widget
To build the text widget from the example at the beginning of this article. You will start by setting up a widget class that extends the WP_Widget class.
In the class constructor you will call the parent constructor and pass it your widget’s base ID and name. Also in the class constructor you will hook into the widgets_init action to register your widget.
Next you will declare the arguments you will use when creating your widget. There are four arguments you must define, before_title , after_title , before_widget , and after_widget . These arguments will define the code that wraps your widgets title and the widget itself.
After defining your arguments, you will define the widgets function. This function takes two parameters, the $args array from before, and the $instance of the widget, and is the function that will process options from the form and display the HTML for the widget on the front-end of your site. In the example above the widget function simply outputs the widget title, while passing it through the widget_title filter. It then out puts a simple widget wrapper and the content of the widget’s text field. As outlined in the example, you can access the options from the widget that are stored in the $instance .
Next you will define the form function. This function takes one parameter, $instance , and outputs the form that the user uses to create the widget in the Widgets admin screen. In the example above, the function starts by defining the $title and $text variables and setting them to the previously entered values, if those values exist. Then it outputs a simple form with a text field for the title and a textarea for the text content.
Lastly you will define the update function. This function takes two parameters, $new_instance and $old_instance , and is responsible for updating your widgets with new options when they are submitted. Here you simply define $instance as an empty array. You then set the title and text keys to the $new_instance values if they exist. You then return $instance .
Finally, when all of the above is defined, you instantiate your new widget class and test your work.
Sample Widget
__( 'A Foo Widget', 'text_domain' ) ) // Args ); > /** * Front-end display of widget. * * @see WP_Widget::widget() * * @param array $args Widget arguments. * @param array $instance Saved values from database. */ public function widget( $args, $instance ) < extract( $args ); $title = apply_filters( 'widget_title', $instance['title'] ); echo $before_widget; if ( ! empty( $title ) ) < echo $before_title . $title . $after_title; >echo __( 'Hello, World!', 'text_domain' ); echo $after_widget; > /** * Back-end widget form. * * @see WP_Widget::form() * * @param array $instance Previously saved values from database. */ public function form( $instance ) < if ( isset( $instance['title'] ) ) < $title = $instance['title']; >else < $title = __( 'New title', 'text_domain' ); >?>
get_field_name( 'title' ); ?>"> get_field_name( 'title' ); ?>" type="text" value="" />
/** * Sanitize widget form values as they are saved. * * @see WP_Widget::update() * * @param array $new_instance Values just sent to be saved. * @param array $old_instance Previously saved values from database. * * @return array Updated safe values to be saved. */ public function update( $new_instance, $old_instance ) < $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; return $instance; >> // class Foo_WidgetThis sample widget can then be registered in the widgets_init hook:
Example with a Namespace
If you use PHP 5.3 with namespaces you should call the constructor directly as in the following example:
and call the register widget with:
Special considerations
If you want to use a widget inside another template file, rather than in a sidebar, you can use the_widget() to display it programmatically. The function accepts widget class names. You pass the widget class name to the function like this:
You may want to use this approach if you need to use a widget in a specific area on a page, such as displaying a list of events next to a form in a section on the front page of your site or displaying an email capture form on a mega-menu alongside your navigation.
the_widget() │ WP 2.8.0
Хуки из функции
Возвращает
Использование
the_widget( $widget, $instance, $args );$widget(строка) (обязательный) Название PHP класса, который отвечает за виджет. см. /wp-includes/default-widgets.php . Виджеты из коробки:
WP_Widget_Pages WP_Widget_Links WP_Widget_Search WP_Widget_Archives WP_Widget_Media WP_Widget_Media_Audio WP_Widget_Media_Image WP_Widget_Media_Video WP_Widget_Media_Gallery WP_Widget_Meta WP_Widget_Calendar WP_Widget_Text WP_Widget_Categories WP_Widget_Recent_Posts WP_Widget_Recent_Comments WP_Widget_RSS WP_Widget_Tag_Cloud WP_Nav_Menu_Widget WP_Widget_Custom_HTML WP_Widget_Block
Подробное описание каждого виджета смотрите ниже. $instance(массив/строка) Параметры виджета (настройки экземпляра класса). Можно указать: массив array(‘dropdown’=>’1’) или строку запроса: ‘dropdown=1&count=1’ . Какие параметры у каждого виджета смотрите ниже. Или зайдите в админку WP Внешний вид > Виджеты , активируйте нужный виджет и посмотрите какие у него есть параметры. Чтобы узнать конкретное название параметра, смотрите последнее значение атрибута name у поля виджета, например у виджета «облако меток» поле «заголовок» равно name=»widget-tag_cloud[2][title]» — значит настройка будет — title . По умолчанию: array() $args(массив) Массив параметров для изменения отображения виджета. Может быть:
- before_widget(строка)
HTML который будет добавлен перед кодом виджета.
По умолчанию:, где %s class виджета.- after_widget(строка)
HTML который будет добавлен после кода виджета.
По умолчанию:- before_title(строка)
HTML который будет добавлен перед кодом заголовка виджета.
По умолчанию:- after_title(строка)
HTML который будет добавлен после кода заголовка виджета.
По умолчанию: