リアクションボタンを追加できた。
スニペットのプラグインを入れて下記の通り対応。
add_filter('the_content','simple_reactions');
add_filter('the_excerpt','simple_reactions');
function simple_reactions($content){
if(is_admin()) return $content;
global $post;
$reactions = [
'like' => '👍 want you',
'love' => '❤️ lover men',
'read' => '👀 Cleanup Clean Lady'
];
$buttons = '<div class="simple-reactions">';
foreach($reactions as $key => $emoji){
$count = (int)get_post_meta($post->ID,'reaction_'.$key,true);
$buttons .= '
<button class="simple-reaction-btn"
data-post="'.$post->ID.'"
data-reaction="'.$key.'"
data-label="'.$emoji.'">
'.$emoji.' '.$count.'
</button>';
}
$buttons .= '</div>';
return $content.$buttons;
}
add_action('wp_footer','simple_reactions_script');
function simple_reactions_script(){ ?>
<script>
document.addEventListener('click', async function(e){
if(!e.target.classList.contains('simple-reaction-btn')) return;
const btn = e.target;
const label = btn.dataset.label;
const form = new FormData();
form.append('action','simple_reaction');
form.append('post_id',btn.dataset.post);
form.append('reaction',btn.dataset.reaction);
const res = await fetch('<?php echo admin_url('admin-ajax.php'); ?>',{
method:'POST',
body:form
});
const count = await res.text();
btn.innerHTML = label + ' ' + count;
});
</script>
<?php }
add_action('wp_ajax_simple_reaction','simple_reaction');
add_action('wp_ajax_nopriv_simple_reaction','simple_reaction');
function simple_reaction(){
$post_id = (int)$_POST['post_id'];
$reaction = sanitize_text_field($_POST['reaction']);
$meta_key = 'reaction_'.$reaction;
$count = (int)get_post_meta($post_id,$meta_key,true);
$count++;
update_post_meta($post_id,$meta_key,$count);
echo $count;
wp_die();
}
「外観 → カスタマイズ → 追加CSS」
.simple-reactions{
display:flex;
gap:10px;
margin-top:8px;
flex-wrap:wrap;
}
.simple-reaction-btn{
background:none;
border:none;
padding:0;
cursor:pointer;
font-size:11px;
line-height:1.2;
color:#888 !important;
opacity:0.85;
}
.simple-reaction-btn:hover{
opacity:1;
}