wpで独自の「いいね」ボタンを設置できるプラグイン『WP Ulike』。
管理画面からある程度の設定はできるのですが、「記事一覧ページにいいねボタンを設置させたい」とか「特定のpostsループにもいいねボタンを取り付けたい!」となると、デフォルトの機能だと存在しないです。
なので、$post_idを渡すことで好きな場所でいいねボタンを生成できるようにしてみました。
※動作確認したWP Ulikeのversionは 2.4.2 、wpのバージョンはWordPress 4.7.3です。
$post_idからulikeボタン を表示させるコード
themeファイルの functions.phpに追記してください。
// Ulike button output;
if( !function_exists('get_the_ulike_btn') ){
function get_the_ulike_btn( $post_id ){
global $wp_ulike_class,$wp_user_IP;
$get_post_meta = get_post_meta($post_id, '_liked', true);
$get_like = $get_post_meta != '' ? $get_post_meta : 0;
$return_userID = $wp_ulike_class->get_reutrn_id();
$theme_class = wp_ulike_get_setting( 'wp_ulike_posts', 'theme');
$data = array(
"id" => $post_id , //Post ID
"user_id" => $return_userID, //User ID (if the user is guest, we save ip as user_id with "ip2long" function)
"user_ip" => $wp_user_IP, //User IP
"get_like" => $get_like, //Number Of Likes
"method" => 'likeThis', //JavaScript method
"setting" => 'wp_ulike_posts', //Setting Key
"type" => 'post', //Function type (post/process)
"table" => 'ulike', //posts table
"column" => 'post_id', //ulike table column name
"key" => '_liked', //meta key
"cookie" => 'liked-' //Cookie Name
);
//call wp_get_ulike function from class-ulike calss
$counter = $wp_ulike_class->wp_get_ulike($data);
$wp_ulike = '<div id="wp-ulike-'.$post_ID.'" class="wpulike '.$theme_class.'">';
$wp_ulike .= '<div class="counter">'.$counter.'</div>';
$wp_ulike .= '</div>';
$wp_ulike .= $wp_ulike_class->get_liked_users($post_ID,'ulike','post_id','wp_ulike_posts');
echo $wp_ulike;
}
}
あとは、好きなとこと(postのループなど)で get_the_ulike_btn( $post_id ); を呼び出してあげれば、ULikeボタンを好きなところで呼び出すことができます。
記事一覧でUlikeボタンを表示させる例
<!-- ループ開始 -->
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="post">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<!-- Ulikeのボタンを表示 -->
<small><?php get_the_ulike_btn( '$post->ID' ); ?></small>
<!-- 日時を表示 -->
<small><?php the_time('F jS, Y'); ?></small>
<!-- 投稿の本文をdiv内に表示 -->
<div class="entry">
<?php the_content(); ?>
</div>
<!-- 投稿のカテゴリーをコンマ区切りで表示 -->
<p class="postmetadata">Posted in <?php the_category(', '); ?></p>
</div> <!-- 最初の div ボックスを閉じる -->
<!-- “else”部分を除いたループ終了 -->
<?php endwhile; endif; ?>
サンプルコードの一部はWordpress Codex 日本語版のこちらのページからお借りさせていただきました。