wp_widgets_init()


WordPressのwp_widgets_init()関数は、ウィジェットエリアを初期化し、ウィジェットを登録するために使用されます。この関数は、テーマやプラグインでウィジェットを追加する際に重要な役割を果たします。

構文

wp_widgets_init();
  • wp_widgets_init()は引数を取りません。

例1: 基本的なウィジェットエリアの登録

この例では、サイドバーにウィジェットエリアを追加します。

function my_theme_widgets_init() { register_sidebar( array( 'name' => 'Main Sidebar', 'id' => 'main-sidebar', 'description' => 'This is the main sidebar.', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } add_action( 'widgets_init', 'my_theme_widgets_init' );

例2: 複数のウィジェットエリアを登録

この例では、複数のウィジェットエリアを一度に登録します。

function my_theme_widgets_init() { register_sidebar( array( 'name' => 'Footer Area 1', 'id' => 'footer-1', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); register_sidebar( array( 'name' => 'Footer Area 2', 'id' => 'footer-2', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } add_action( 'widgets_init', 'my_theme_widgets_init' );

例3: カスタムウィジェットの登録

この例では、カスタムウィジェットを作成し、登録します。

class My_Custom_Widget extends WP_Widget { function __construct() { parent::__construct( 'my_custom_widget', 'My Custom Widget', array( 'description' => 'A custom widget example.', ) ); } public function widget( $args, $instance ) { echo $args['before_widget']; echo $args['before_title'] . 'Custom Widget Title' . $args['after_title']; echo 'This is my custom widget content.'; echo $args['after_widget']; } } function register_my_custom_widget() { register_widget( 'My_Custom_Widget' ); } add_action( 'widgets_init', 'register_my_custom_widget' );

例4: ウィジェットエリアの条件付き表示

この例では、特定の条件でウィジェットエリアを表示します。

function my_theme_widgets_init() { if ( is_home() ) { register_sidebar( array( 'name' => 'Home Sidebar', 'id' => 'home-sidebar', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } } add_action( 'widgets_init', 'my_theme_widgets_init' );

例5: ウィジェットエリアの削除

この例では、特定のウィジェットエリアを削除します。

function remove_default_widgets() { unregister_sidebar( 'sidebar-1' ); } add_action( 'widgets_init', 'remove_default_widgets', 11 );

例6: ウィジェットエリアのカスタマイズ

この例では、ウィジェットエリアのHTML構造をカスタマイズします。

function my_theme_widgets_init() { register_sidebar( array( 'name' => 'Custom Sidebar', 'id' => 'custom-sidebar', 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'my_theme_widgets_init' );

注意点

  • wp_widgets_init()は、テーマのfunctions.phpファイル内で使用されることが一般的です。
  • ウィジェットエリアのIDは一意である必要があります。
  • ウィジェットエリアの登録は、widgets_initアクションフックを使用して行います。

関連機能: