いいねボタン($wpdb)
テーブルの作成
テーブル名:wp_likenumber
id | Auto Increment | ||
post_id | INT | 投稿ID | |
post_title | TEXT | 記事タイトル | |
like_count | INT | いいね数 |
「post_id=現在の記事のID」のレコードがなければ追加
function insert_if_not_exist() {
global $wpdb;
$table_name = $wpdb->prefix . 'likecount';
$post_id = get_the_ID();
$post_title = get_the_title($post_id);
$existed = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE post_id = %d",
$post_id
)
);
$data = array(
'post_id' => $post_id,
'post_title' => $post_title,
'like_count' => 0,
);
$format = array(
'%d',
'%s',
'%d',
);
if(!$existed) {
$wpdb->insert($table_name, $data, $format);
}
}
add_action('save_post', 'insert_if_not_exist');
functions.phpに記載
add_action(‘wp’, ‘xxx’)はテーマのテンプレートがロードされたときに実行される
add_action(‘save_post’, ‘xxx’)とすることで、記事の登録や更新時の処理にフックをかけられる
いいねボタンの設置
<form method='post' action=''>
<label for='like' style='display:none;'></label>
<input type='text' name='like' id='like'>
<button type='submit' name='like_button'>いいね</button>
</form>
いいねボタンを押すとデータベースが更新されるロジックを記述
function like_count_update() {
global $wpdb;
if(isset($_POST['like_button'])) {
$table_name = $wpdb->prefix . 'likecount';
$post_id = get_the_ID();
$updated = $wpdb->query(
$wpdb->prepare(
"UPDATE $table_name SET like_count = like_count + 1 WHERE post_id = %d",
$post_id
)
);
// アップデートされたか確認
if($updated !== false) {
$results = $wpdb->get_results("SELECT * FROM $table_name WHERE post_id = $post_id");
foreach($results as $result){
echo $result->like_count . "に更新されました";
}
} else {
echo '更新失敗';
}
}
}
add_action('wp','like_count_update');
更新されたいいね数の表示
<?php
global $wpdb;
$table_name = $wpdb->prefix . 'likecount';
$post_id = get_the_ID();
$results = $wpdb->get_results("SELECT * FROM $table_name WHERE post_id = $post_id");
foreach($results as $result) {
echo "<p>記事タイトル</p>" . $result->post_title . "<br>";
echo "<p>現在のいいね数:</p>" . $result->like_count . "<br>";
}
?>
補足:いいね数のランキングページ
<?php
global $wpdb;
$table_name = $wpdb->prefix . 'likecount';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY like_count DESC LIMIT 20");
$i = 1;
foreach($results as $result) {
echo '<article>';
echo '<span>' . $i . '位</span>';
echo '<a href=' . get_permalink($result->post_id) . '>';
echo get_the_post_thumbnail($result->post_id);
echo '</a>';
echo '<div>';
echo '<h2>' . $result->post_title . '</h2>';
echo '<time>' . get_the_date("Y/m/d", $result->post_id) . '</time>';
echo '<span>いいね数:' . $result->like_count . '</span>';
echo '</div>';
echo '</article>';
$i++;
}
?>