Для вывода в sidebar Вам нужно пройти следующие этапы
- Инициализировать свой виджет - прописать вызов его в functions.php вашей темы либо в плагине
Примерный код
class My_Widget extends WP_Widget {
public function __construct() {
// actual widget processes
}
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
}
}
add_action( 'widgets_init', 'wpdocs_register_widgets' );
function wpdocs_register_widgets() {
register_widget( 'My_Widget' );
}
https://developer.wordpress.org/themes/functionality/widgets/
- Реализовать вывод списка категорий
<?php
if ( is_singular( 'services' ) ) {
$post_id = get_the_ID();
$terms = get_the_terms( $post_id, 'services_category'); ?>
<ul>
<?php foreach ($terms as $term) : ?>
<?php if ($term -> parent) : ?>
<li><a href="<?php echo get_term_link( $term_ ); ?>"><?php echo $term -> name ; ?></a></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php
}
В админке назначить вывод вашего виджета в нужный сайдбар
Примерный код виджета
function services_category_register_widget() {
register_widget( 'services_category_widget' );
}
add_action( 'widgets_init', 'services_category_register_widget' );
class services_category_widget extends WP_Widget {
function __construct() {
parent::__construct(
// widget ID
'services_category_widget',
// widget name
__('Services Category Widget', ' services_category_widget_domain'),
// widget description
array( 'description' => __( 'Services Categor Widget', 'services_category_widget_domain' ), )
);
}
public function widget( $args, $instance ) {
if ( is_singular( 'services' ) ) {
$post_id = get_the_ID();
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'];
//if title is present
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
//output
?>
<?php $terms = get_the_terms( $post_id, 'services_category'); ?>
<ul>
<?php foreach ($terms as $term) : ?>
<?php if ($term -> parent) : ?>
<li><a href="<?php echo get_term_link( $term_ ); ?>"><?php echo $term -> name ; ?></a></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php
echo $args['after_widget'];
}
}
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) )
$title = $instance[ 'title' ];
else
$title = __( 'Default Title', 'services_category_widget_domain' );
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}