WordPress 网站里增加访客互动、展示文章热度的时候,除了阅读数、评论数外,还有个有趣的元素,那就是赞,如 QQ 空间里的说说一样,赞!
以前也发过类似的插件给大家,喜欢用插件的可以进 《WordPress 点赞 插件版》,而今天介绍的就是纯代码的形式,不喜欢用插件的朋友会喜欢的方式来实现 WordPress 点赞功能!
下面就直接给教程吧,教程资源来自 WPku
将下面的代码加入到你的functions.php
中
- add_action('wp_ajax_nopriv_bigfa_like', 'bigfa_like');
- function bigfa_like(){
- global $wpdb,$post;
- $id = $_POST["um_id"];
- $action = $_POST["um_action"];
- if ( $action == 'ding'){
- $bigfa_raters = get_post_meta($id,'bigfa_ding',true);
- $expire = time() + 99999999;
- $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
- setcookie('bigfa_ding_'.$id,$id,$expire,'/',$domain,false);
- if (!$bigfa_raters || !is_numeric($bigfa_raters)) {
- update_post_meta($id, 'bigfa_ding', 1);
- else {
- $id, 'bigfa_ding', ($bigfa_raters + 1));
- }
- echo get_post_meta($id,'bigfa_ding',true);
- }
- die;
-
- $.fn.postLike = function() {
- if ($(this).hasClass('done')) {
- return false;
- else {
- $(this).addClass('done');
- var id = $(this).data("id"),
- action = $(this).data('action'),
- this).children('.count');
- var ajax_data = {
- "bigfa_like",
- um_id: id,
- };
- "/wp-admin/admin-ajax.php", ajax_data,
- function(data) {
- });
- return false;
- }
- $(document).on("click", ".favorite",
- function() {
- $(this).postLike();
-
- <div class="post-like">
- "javascript:;" data-action="ding" data-id="<?php the_ID(); ?>" class="favorite<?php if(isset($_COOKIE['bigfa_ding_'.$post->ID])) echo ' done';?>"> 喜欢 <span class="count">
- <?php if( get_post_meta($post->ID,'bigfa_ding',true) ){
- echo get_post_meta($post->ID,'bigfa_ding',true);
- } else {
- echo '0';
- }?></span>
- </div>
参考 css 样式
- .post-like{text-align:center;padding:10px}
- background-color:#21759B;border-radius: 3px;color: #FFFFFF;font-size: 12px;padding: 5px 10px;text-decoration: none;outline:none}
- .post-like a.done, .post-like a:hover{background-color:#eee;color:#21759B;}
- cursor:not-allowed}