Wordpress Sentryでサイドバーウィジェットにもプロフィールを表示できるようにする
2022-12-31T02:29:20.484Z
Sentryは優秀なWPテーマで、カスタマイズ>投稿ページ設定>記事下コンテンツで使えるprofile
をウィジェットでも使えるようにしてサイドバーに表示したかった。
基本的には参考リンクのようにウィジェットを追加して、Sentryが用意してくれているse-profile.php
を呼び出すだけ。ただ本来は記事下コンテンツ用なので、サイドバーで表示するように追加CSSを少し書いた。
// functions.php
// add profile widget
class My_Profile_Widget extends WP_Widget{
/**
* Widgetを登録する
*/
function __construct() {
parent::__construct(
'My_Profile_Widget',
'[S]プロフィール',
array( 'description' => 'プロフィールを表示します', )
);
}
/**
* 表側の Widget を出力する
*
* @param array $args 'register_sidebar'で設定した「before_title, after_title, before_widget, after_widget」が入る
* @param array $instance Widgetの設定項目
*/
public function widget( $args, $instance ) {
$title = empty( $instance['title'] ) ? '' : $instance['title'];
echo $args['before_widget'];
if ( ! empty( $title ) ) {
echo $args['before_title'] . $title . $args['after_title'];
}
get_template_part( 'parts/se-profile' );
echo $args['after_widget'];
}
/**
* 管理画面のウィジェット設定フォーム
*
* @param array $instance 現在のオプション値が渡される。
*/
public function form( $instance ) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">タイトル</label>
<input type="text"
class="widefat"
id="<?php echo $this->get_field_id( 'title' ); ?>"
name="<?php echo $this->get_field_name( 'title' ); ?>"
value ="<?php echo $title; ?>" />
</p>
<?php
}
/** 新しい設定データが適切なデータかどうかをチェックする。
* 必ず$instanceを返す。さもなければ設定データは保存(更新)されない。
*
* @param array $new_instance form()から入力された新しい設定データ
* @param array $old_instance 前回の設定データ
* @return array 保存(更新)する設定データ。falseを返すと更新しない。
*/
function update($new_instance, $old_instance) {
// 一時的に以前のオプションを別変数に退避
$instance = $old_instance;
// タイトル値を無害化(サニタイズ)
$instance['title'] = sanitize_text_field( $new_instance['title'] );
return $new_instance;
}
}
add_action( 'widgets_init', function () {
register_widget( 'My_Profile_Widget' );
} );
/* style.css */
.sidebar-main #profile-card .inner-content {
display: block;
}
.sidebar-main #profile-card .avator img {
max-width: 144px
}
参考リンク
https://liginc.co.jp/web/wp/112370