wordpress popular postは便利なプラグインです。
ショートコードやテンプレートタグで自由にランキングのHTMLを出力できます。
ランキングのサムネイルを見ていたら、imgタグに付けていたレスポンシブ対応のsrcsetなどが綺麗さっぱり消えていることに気が付きました。
原因を色々調べていくと、wordpress popular postはHTMLを出力する時に、wp_ksesを通していて、そこでimgタグからsrcsetなどが消えていました。
wp_kses自体はwordpress popular postとは関係ないのですが、さすがにsrcsetが無いのはまずいので回避方法を見つけて対処しました。
この記事では、wordpress popular postのテンプレートタグやショートコードを使った時にimgタグが期待と違うものになってしまったという人や、wp_ksesを通すとimgタグが変わってしまうという問題の解決方法になります。
WordPress popular postのHTML最終出力部分
ショートコード(テンプレートタグも同じ)の最後でwp_ksesを通っています。
$this->output->set_data($popular_posts->get_posts());
$this->output->set_public_options($shortcode_ops);
$this->output->build_output();
$shortcode_content .= $this->output->get_output();
// Sanitize and return shortcode HTML
$allowed_tags = wp_kses_allowed_html('post');
if ( isset($allowed_tags['form']) ) {
unset($allowed_tags['form']);
}
if ( ! empty($shortcode_ops['theme']['name']) ) {
$allowed_tags['style'] = [
'id' => 1,
'nonce' => 1,
];
}
return wp_kses($shortcode_content, $allowed_tags);
}
}
wp_ksesはimgタグからsrcsetを削除する
wp_ksesは、使用禁止のタグを決めて、そのタグが含まれていると削除してくれる関数です。
imgタグのsrcsetは使用禁止のタグになっているので削除されてしまいます。
使用禁止のタグは自分で変更できますので、その部分をフックで変更すれば大丈夫です。
function starter_wpkses_post_tags( $tags, $context ) {
$tags['img']['sizes'] = true;
$tags['img']['srcset'] = true;
$tags['source'] = array(
'srcset' => true,
'sizes' => true,
'type' => true,
);
return $tags;
}
add_filter( 'wp_kses_allowed_html', 'starter_wpkses_post_tags', 10, 2 );
まとめ
WordPress popular postはフックが用意されているので自由にカスタマイズできますが、最終出力段階でwp_ksesを通っているので、意図しないようなHTML変更が入ってしまうようでした。
今回のカスタマイズはwordpress popular post以外にも影響しますが、一般的な内容ですので、特に影響はないはずです。