0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【WordPress】該当文字の登場数をカウントして計測するプラグイン

0
Last updated at Posted at 2026-02-26

ポートフォリオのため、高額商品のレビューサイトを制作している。
商談のおかしいポイントをカウントすべく、本文から違和感などのフレーズを抽出して文末にカウントするものを作った。

#おおよその構造

  • もやもや表記の飾りと、もやもやワードを配列にする。
  • 本文からタグを外す。
  • foreachで配列からワード→絵文字にする。
  • substr_count関数で検索対象からワードを探す。
  • もし0より多かったら、カウント数を示す。
  • もしパーツがあれば、パーツを/で区切ってくっつける。
  • 本文の最後にくっつける。

#パーツ別覚書

/**
 * Plugin Name: sr_add_badges
 * Description: 違和感にバッヂをつけるプラグイン
 * Version: 1.0.0
 */

冒頭の設定。一字一句間違えない。定型その1.

if (!defined('ABSPATH')) { 
  exit;
}

定型その2.直access防止の門番。

add_filter('the_content', 'sr_show_judge');

the_contentはthe_content()関数が本文を取り出して整形する途中のフィルター。
add_filter の第2引数は「関数名の文字列」

    if (is_admin()) return $content;
    if (!is_singular()) return $content;

contentの要素はあちこちで使われているので、その都度フィルターが発生してはいけないので、管理画面やカスタムページでは本文のみを戻す。

$count = substr_count($plain, $word);

PHP組み込み関数。前者plainが検索対象、後者wordが検索ワード。

完成品

/**
 * Plugin Name: sr_add_badges
 * Description: 違和感にバッヂをつけるプラグイン
 * Version: 1.0.0
 */

if (!defined('ABSPATH')) { //提携、直access防止の門番。
  exit;
}

add_filter('the_content', 'sr_show_judge');

$moyamoya = [
    "違和感" => "⚠️",
    "誠実" => "✨",
    "保留" => "💭",
    "要検証" => "🤷",
];

function sr_show_judge($content) {
    global $moyamoya;
    
    if (is_admin()) return $content;
    if (!is_singular()) return $content;

    $plain = wp_strip_all_tags($content);//contentは記事本文。wp_strip_all_tagsはタグを外す。
    $parts = []; //初期化。絵文字とカウントのセットの配列
    $append = ''; //初期化。

    foreach ($moyamoya as $word => $emoji){
            $count = substr_count($plain, $word);
            if($count > 0) {
                $parts[] = "$emoji{$word} x {$count}";
            }
        }

    if($parts) {
        $judge_text = '判定:' . implode(' / ', $parts);
        $append = "<div class=\"sr-judge-badges\">{$judge_text}</div>";
        return $content.$append;
    } else {
        return $content;
    }
}

##完成イメージ
image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?