【WordPress】カスタム投稿タイプの最新投稿を表示するウィジェットの作成

WordPressでウィジェットを自作する方法をもとにして、カスタム投稿タイプの最新投稿を表示するウィジェットを作成していきます。

WordPressでは、デフォルトで投稿の最新投稿を表示するウィジェットがあります。

このウィジェットのコードを基にして、カスタム投稿タイプの最新投稿を表示するウィジェットの作成を進めます。

まずは投稿の最新投稿を表示するウィジェットのコードを解説し、そのあとで必要な箇所を修正していきます。

投稿の最新投稿を表示するウィジェットのコード解説

投稿の最新投稿を表示するウィジェットのクラスは、WP_Widget_Recent_Postsクラスであり、/wp_includes/widgets/class-wp-widget-recent-posts.phpに記述されています。

WP_Widget_Recent_Postsクラスには、次の4つの関数が定義されています。

  • __construct関数
  • widget関数
  • update関数
  • form関数

それぞれの関数について、詳しく見ていきます。

__construct関数

	/**
	 * Sets up a new Recent Posts widget instance.
	 *
	 * @since 2.8.0
	 */
	public function __construct() {
		$widget_ops = array(
			'classname'                   => 'widget_recent_entries',
			'description'                 => __( 'Your site’s most recent Posts.' ),
			'customize_selective_refresh' => true,
		);
		parent::__construct( 'recent-posts', __( 'Recent Posts' ), $widget_ops );
		$this->alt_option_name = 'widget_recent_entries';
	}

__construct関数で行なっていることは、次のことです。

  • 親(WP_Widgetクラス)のコンストラクタを呼び出し、ウィジェットのベースIDとしてrecent-posts、ウィジェットの名前としてRecent Posts、オプション項目として$widget_opsを渡す
  • WP_Widget_Recent_Postsクラスのalt_option_nameにwidget_recent_entriesを指定する

WP_Widgetクラスの__constructでは、次のように記載されています。

        $this->widget_options  = wp_parse_args(
            $widget_options,
            array(
                'classname'                   => $this->option_name,
                'customize_selective_refresh' => false,
            )
        );

wp_parse_argsに配列を渡すと、array_mergeにより同じキーの値は上書きされます。

つまりWP_Widget_Recent_Postsクラスの$widget_optionsの値が次のようになります。

$widget_options = array(
    'classname'                   => 'widget_recent_entries',
    'description'                 => __( 'Your site’s most recent Posts.' ),
    'customize_selective_refresh' => true,
);

customize_selective_refreshは、Implementing Selective Refresh Support for Widgetsに説明が記載されています。

If your widget lacks any dynamic functionality with JavaScript initialization, adding support just requires adding a customize_selective_refresh flag to the $widget_options param when constructing the WP_Widget subclass.

カスタマイザーで動的な更新を行いたい場合は、customize_selective_refreshtrueを指定します。

alt_option_nameは、option_nameの代替として設定するものです。

つまり、$option_nameがrecent-posts、$alt_option_nameがwidget_recent_entriesとして設定されます。

widget関数

	/**
	 * Outputs the content for the current Recent Posts widget instance.
	 *
	 * @since 2.8.0
	 *
	 * @param array $args     Display arguments including 'before_title', 'after_title',
	 *                        'before_widget', and 'after_widget'.
	 * @param array $instance Settings for the current Recent Posts widget instance.
	 */
	public function widget( $args, $instance ) {
		if ( ! isset( $args['widget_id'] ) ) {
			$args['widget_id'] = $this->id;
		}

		$default_title = __( 'Recent Posts' );
		$title         = ( ! empty( $instance['title'] ) ) ? $instance['title'] : $default_title;

		/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );

		$number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5;
		if ( ! $number ) {
			$number = 5;
		}
		$show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false;

		$r = new WP_Query(
			/**
			 * Filters the arguments for the Recent Posts widget.
			 *
			 * @since 3.4.0
			 * @since 4.9.0 Added the `$instance` parameter.
			 *
			 * @see WP_Query::get_posts()
			 *
			 * @param array $args     An array of arguments used to retrieve the recent posts.
			 * @param array $instance Array of settings for the current widget.
			 */
			apply_filters(
				'widget_posts_args',
				array(
					'posts_per_page'      => $number,
					'no_found_rows'       => true,
					'post_status'         => 'publish',
					'ignore_sticky_posts' => true,
				),
				$instance
			)
		);

		if ( ! $r->have_posts() ) {
			return;
		}
		?>

		<?php echo $args['before_widget']; ?>

		<?php
		if ( $title ) {
			echo $args['before_title'] . $title . $args['after_title'];
		}

		$format = current_theme_supports( 'html5', 'navigation-widgets' ) ? 'html5' : 'xhtml';

		/** This filter is documented in wp-includes/widgets/class-wp-nav-menu-widget.php */
		$format = apply_filters( 'navigation_widgets_format', $format );

		if ( 'html5' === $format ) {
			// The title may be filtered: Strip out HTML and make sure the aria-label is never empty.
			$title      = trim( strip_tags( $title ) );
			$aria_label = $title ? $title : $default_title;
			echo '<nav role="navigation" aria-label="' . esc_attr( $aria_label ) . '">';
		}
		?>

		<ul>
			<?php foreach ( $r->posts as $recent_post ) : ?>
				<?php
				$post_title   = get_the_title( $recent_post->ID );
				$title        = ( ! empty( $post_title ) ) ? $post_title : __( '(no title)' );
				$aria_current = '';

				if ( get_queried_object_id() === $recent_post->ID ) {
					$aria_current = ' aria-current="page"';
				}
				?>
				<li>
					<a href="<?php the_permalink( $recent_post->ID ); ?>"<?php echo $aria_current; ?>><?php echo $title; ?></a>
					<?php if ( $show_date ) : ?>
						<span class="post-date"><?php echo get_the_date( '', $recent_post->ID ); ?></span>
					<?php endif; ?>
				</li>
			<?php endforeach; ?>
		</ul>

		<?php
		if ( 'html5' === $format ) {
			echo '</nav>';
		}

		echo $args['after_widget'];
	}

$instance変数から、設定値があれば、各変数に保持を行います。

そして、WP_Query関数を利用して、ステイタスが公開済みになっている投稿を取得します。

取得した最新の投稿をforeach関数を利用して、リストを使用して表示するという流れになっています。

update関数

	/**
	 * Handles updating the settings for the current Recent Posts widget instance.
	 *
	 * @since 2.8.0
	 *
	 * @param array $new_instance New settings for this instance as input by the user via
	 *                            WP_Widget::form().
	 * @param array $old_instance Old settings for this instance.
	 * @return array Updated settings to save.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance              = $old_instance;
		$instance['title']     = sanitize_text_field( $new_instance['title'] );
		$instance['number']    = (int) $new_instance['number'];
		$instance['show_date'] = isset( $new_instance['show_date'] ) ? (bool) $new_instance['show_date'] : false;
		return $instance;
	}

最新の投稿では、タイトル、表示する投稿数、日付の表示を3つの設定項目があります。

これらの項目に対して、入力された値のバリデーション及び無害化を行います。

form関数

	/**
	 * Outputs the settings form for the Recent Posts widget.
	 *
	 * @since 2.8.0
	 *
	 * @param array $instance Current settings.
	 */
	public function form( $instance ) {
		$title     = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
		$number    = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
		$show_date = isset( $instance['show_date'] ) ? (bool) $instance['show_date'] : false;
		?>
		<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 $title; ?>" />
		</p>

		<p>
			<label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to show:' ); ?></label>
			<input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" />
		</p>

		<p>
			<input class="checkbox" type="checkbox"<?php checked( $show_date ); ?> id="<?php echo $this->get_field_id( 'show_date' ); ?>" name="<?php echo $this->get_field_name( 'show_date' ); ?>" />
			<label for="<?php echo $this->get_field_id( 'show_date' ); ?>"><?php _e( 'Display post date?' ); ?></label>
		</p>
		<?php
	}

form関数では、管理画面でのタイトル、表示する投稿数、日付の表示の設定項目の入力が行えるように実装を行います。

$instance変数には、データベースに保存された値が含まれています。

修正する方針

form関数で、表示するカスタム投稿タイプを選択できるように実装を行います。

そして、widget関数で選択したカスタム投稿タイプの投稿が表示されるようにします。

update関数も忘れずに、カスタム投稿タイプについて実装を行います。

WordPressでカスタム投稿タイプの最新投稿を表示するウィジェット

__construct関数

WordPressにデフォルトで登録されているウィジェットのコードを使用するので、クラス名やウィジェットのベースIDが重複しないように変更します。

	/**
	 * Sets up a new Recent Posts widget instance.
	 *
	 * @since 2.8.0
	 */
	public function __construct() {
		$widget_ops = array(
			'classname'                   => 'widget_recent_cpt_entries',
			'description'                 => __( 'Your site&#8217;s most recent CPT Posts.' ),
			'customize_selective_refresh' => true,
		);
		parent::__construct( 'recent-cpt-posts', __( 'Recent CPT Posts' ), $widget_ops );
		$this->alt_option_name = 'widget_recent_cpt_entries';
	}

$widget_opsに設定するクラスネームと、__constructで渡すベースIDを変更します。

$alt_option_nameも使用する予定はありませんが、変更しておきます。

widget関数

WP_Query関数を利用して、指定したカスタム投稿タイプの投稿を取得します。

指定するためのカスタム投稿タイプは$instanceより、管理画面で設定したカスタム投稿タイプを取得します。

$post_type = ! empty( $instance['post_type']) ? $instance['post_type'] : '';

もともとWP_Query内にあった、apply_filtersは利用する予定はないので、はずしておきました。

そして、追加のパラメータとしてpost_typeを指定して、管理画面で設定したカスタム投稿タイプを取得します。

$r = new WP_Query(
    array(
        'post_type'           => $post_type,
        'posts_per_page'      => $number,
        'no_found_rows'       => true,
        'post_status'         => 'publish',
        'ignore_sticky_posts' => true,
    )
);

基本的には、WP_Queryで取得する投稿を変更するだけで、他のところは変更しません。

update関数

update関数では、カスタム投稿タイプを取得するpost_typeに関する記述を追加します。

$instance['post_type']    = (string) $new_instance['post_type'];

form関数

form関数では、カスタム投稿タイプに関する記述を追加します。

設定できるカスタム投稿タイプは、get_post_type関数を利用して_builtinをfalseにすることでデフォルトである投稿・固定ページの投稿タイプを取得しないようにします。

$post_type     = isset( $instance['post_type'] ) ? ( $instance['post_type'] ) : '';
<p>
    <label for="<?php echo esc_attr( $this->get_field_id( 'post_type' ) ); ?>"><?php _e( 'カスタム投稿タイプ:' ); ?></label>
    <select name="<?php echo esc_attr( $this->get_field_name( 'post_type' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'post_type' ) ); ?>" class="widefat">
    <?php
        $post_types = get_post_types( array( 'public' => true, '_builtin' => false ), 'objects' );

        foreach ($post_types as $key => $post_type) { ?>
            <option value="<?php echo $key ?>"><?php echo $post_type->label ?></option>
    <?php } ?>
    </select>
</p>

最終的なコード

// ウィジェットの作成 
class recent_cpt_widget extends WP_Widget {
  
    // コンストラクタの実装部分
    public function __construct() {
        $widget_ops = array(
            'classname'                   => 'widget_recent_cpt_entries',
            'description'                 => __( 'Your site&#8217;s most recent CPT Posts.' ),
            'customize_selective_refresh' => true,
        );
        parent::__construct( 'recent-cpt-posts', __( 'Recent CPT Posts' ), $widget_ops );
        $this->alt_option_name = 'widget_recent_cpt_entries';
    }
   
    // フロントエンドの実装部分
    /**
     * Outputs the content for the current Recent Posts widget instance.
     *
     * @since 2.8.0
     *
     * @param array $args     Display arguments including 'before_title', 'after_title',
     *                        'before_widget', and 'after_widget'.
     * @param array $instance Settings for the current Recent Posts widget instance.
     */
    public function widget( $args, $instance ) {
        if ( ! isset( $args['widget_id'] ) ) {
            $args['widget_id'] = $this->id;
        }
     
        $default_title = __( 'Recent Posts' );
        $title         = ( ! empty( $instance['title'] ) ) ? $instance['title'] : $default_title;
     
        /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
        $title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
		
		$post_type = ! empty( $instance['post_type']) ? $instance['post_type'] : '';
     
        $number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5;
        if ( ! $number ) {
            $number = 5;
        }
        $show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false;
		
		$r = new WP_Query(
                array(
					'post_type'           => $post_type,
                    'posts_per_page'      => $number,
                    'no_found_rows'       => true,
                    'post_status'         => 'publish',
                    'ignore_sticky_posts' => true,
                )
        );
     
        if ( ! $r->have_posts() ) {
            return;
        }
        ?>
     
        <?php echo $args['before_widget']; ?>
     
        <?php
        if ( $title ) {
            echo $args['before_title'] . $title . $args['after_title'];
        }
     
        $format = current_theme_supports( 'html5', 'navigation-widgets' ) ? 'html5' : 'xhtml';
     
        /** This filter is documented in wp-includes/widgets/class-wp-nav-menu-widget.php */
        $format = apply_filters( 'navigation_widgets_format', $format );
     
        if ( 'html5' === $format ) {
            // The title may be filtered: Strip out HTML and make sure the aria-label is never empty.
            $title      = trim( strip_tags( $title ) );
            $aria_label = $title ? $title : $default_title;
            echo '<nav role="navigation" aria-label="' . esc_attr( $aria_label ) . '">';
        }
        ?>
     
        <ul>
            <?php foreach ( $r->posts as $recent_post ) : ?>
                <?php
                $post_title   = get_the_title( $recent_post->ID );
                $title        = ( ! empty( $post_title ) ) ? $post_title : __( '(no title)' );
                $aria_current = '';
     
                if ( get_queried_object_id() === $recent_post->ID ) {
                    $aria_current = ' aria-current="page"';
                }
                ?>
                <li>
                    <a href="<?php the_permalink( $recent_post->ID ); ?>"<?php echo $aria_current; ?>><?php echo $title; ?></a>
                    <?php if ( $show_date ) : ?>
                        <span class="post-date"><?php echo get_the_date( '', $recent_post->ID ); ?></span>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
     
        <?php
        if ( 'html5' === $format ) {
            echo '</nav>';
        }
     
        echo $args['after_widget'];
    }
           
    // バックエンド(管理画面)の実装部分 
    /**
     * Outputs the settings form for the Recent Posts widget.
     *
     * @since 2.8.0
     *
     * @param array $instance Current settings.
     */
    public function form( $instance ) {
        $title     = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
        $post_type     = isset( $instance['post_type'] ) ? ( $instance['post_type'] ) : '';
        $number    = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
        $show_date = isset( $instance['show_date'] ) ? (bool) $instance['show_date'] : false;
        ?>
        <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 $title; ?>" />
        </p>

        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'post_type' ) ); ?>"><?php _e( 'カスタム投稿タイプ:' ); ?></label>
            <select name="<?php echo esc_attr( $this->get_field_name( 'post_type' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'post_type' ) ); ?>" class="widefat">
            <?php
                $post_types = get_post_types( array( 'public' => true, '_builtin' => false ), 'objects' );
    
                foreach ($post_types as $key => $post_type) { ?>
                    <option value="<?php echo $key ?>"><?php echo $post_type->label ?></option>
            <?php } ?>
			</select>
		</p>
     
        <p>
            <label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to show:' ); ?></label>
            <input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" />
        </p>
     
        <p>
            <input class="checkbox" type="checkbox"<?php checked( $show_date ); ?> id="<?php echo $this->get_field_id( 'show_date' ); ?>" name="<?php echo $this->get_field_name( 'show_date' ); ?>" />
            <label for="<?php echo $this->get_field_id( 'show_date' ); ?>"><?php _e( 'Display post date?' ); ?></label>
        </p>
        <?php
    }
       
    // 更新処理の実装部分(バックエンド(管理画面)でウィジェットの設定変更が行われた際)
    /**
     * Handles updating the settings for the current Recent Posts widget instance.
     *
     * @since 2.8.0
     *
     * @param array $new_instance New settings for this instance as input by the user via
     *                            WP_Widget::form().
     * @param array $old_instance Old settings for this instance.
     * @return array Updated settings to save.
     */
    public function update( $new_instance, $old_instance ) {
        $instance              = $old_instance;
        $instance['title']     = sanitize_text_field( $new_instance['title'] );
        $instance['post_type']    = (string) $new_instance['post_type'];
        $instance['number']    = (int) $new_instance['number'];
        $instance['show_date'] = isset( $new_instance['show_date'] ) ? (bool) $new_instance['show_date'] : false;
        return $instance;
    }
  
}

function register_cpt_widget() {
    register_widget( 'recent_cpt_widget' );
}
add_action( 'widgets_init', 'register_cpt_widget' );

修正点
form関数で、option要素でselectedの実装

よかったらシェアしてね!
  • URLをコピーしました!