最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

post meta - Like & Dislike functionality using JavaScript

programmeradmin0浏览0评论

I want to add Like & Dislike functionality into my custom post type, called game.

I have placed like and dislike icon links in my post footer.

Desired Behaviour:

When a user clicks the like icon, I want to check if (s)he already voted for it and if not then create or update post like count meta key inside the post meta and same goes for the user meta.

Problem:

The problem is when a user clicks the like button, I have to handle it inside the JavaScript but I am not sure how to call

set_post_meta($post->ID)

or

update_post_meta($post->ID)

from JavaScript.

Loop:

<?php while ( $r->have_posts() ) : $r->the_post();?>
    <?php if (has_post_thumbnail()): ?>
        <?php the_post_thumbnail('small'); ?>
    <?php endif;?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <div class="game-footer">
        <div class="like-dislike-btn-div">
            <i class="game-footer-like-btn fa fa-thumbs-o-up">0</i>
            <i class="game-footer-dislike-btn fa  fa-thumbs-o-down">0</i>
        </div>
    </div>
<?php  endwhile; ?>

I want to add Like & Dislike functionality into my custom post type, called game.

I have placed like and dislike icon links in my post footer.

Desired Behaviour:

When a user clicks the like icon, I want to check if (s)he already voted for it and if not then create or update post like count meta key inside the post meta and same goes for the user meta.

Problem:

The problem is when a user clicks the like button, I have to handle it inside the JavaScript but I am not sure how to call

set_post_meta($post->ID)

or

update_post_meta($post->ID)

from JavaScript.

Loop:

<?php while ( $r->have_posts() ) : $r->the_post();?>
    <?php if (has_post_thumbnail()): ?>
        <?php the_post_thumbnail('small'); ?>
    <?php endif;?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <div class="game-footer">
        <div class="like-dislike-btn-div">
            <i class="game-footer-like-btn fa fa-thumbs-o-up">0</i>
            <i class="game-footer-dislike-btn fa  fa-thumbs-o-down">0</i>
        </div>
    </div>
<?php  endwhile; ?>
Share Improve this question edited Mar 27, 2020 at 15:01 WordPress Speed 2,2833 gold badges19 silver badges34 bronze badges asked Mar 27, 2020 at 9:04 PrismaPrisma 191 silver badge9 bronze badges 2
  • all this will happen for a logged in user. right?? – BlueSuiter Commented Mar 27, 2020 at 9:24
  • @BlueSuiter Yes! It will happen for logged in users. – Prisma Commented Mar 27, 2020 at 9:48
Add a comment  | 

2 Answers 2

Reset to default 2

I hope you are doing well. Here, I am sharing code for recording likes. The code for single.php have the javascript code for making an ajax call to a wp function. This wp function have the code to store like expressions and it will return you the total number of like expressions recorded on post.

I have curated it for only the Logged in users.

Place this code in your functions.php

/* Ajax call */
add_action('wp_ajax_likeExpression', 'likeExpression');
function likeExpression() {
    if(is_user_logged_in()){
        $post_id = $_GET['post_id'];
        $userId = get_current_user_id();
        $metaKey = '_like_on_game_post_';
        $userLikes = get_user_meta($userId, $metaKey, true);

        if(empty($userLikes)){
            update_user_meta($userId, $metaKey, wp_json_encode([$post_id]));
        }else{
            $userLikes = json_decode($userLikes);
            if(!in_array($post_id, $userLikes)){
                array_push($userLikes, $post_id);
                update_user_meta($userId, $metaKey, wp_json_encode($userLikes));
            }
        }

        $postLikeCount = get_post_meta($post_id, '_like_count_on_post_', true);
        update_post_meta($post_id, '_like_count_on_post_', ++$postLikeCount);
        exit($postLikeCount);
    }
}

Place this in single.php, (before footer ends)

<?php if(is_user_logged_in()): ?>
    <script>
    jQuery(function($){
        $('.game-footer-like-btn').on('click', function(){
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php?action=likeExpression&post_id='.get_the_ID()) ?>',
                method: 'get',
            }).done(function(res){
                console.log(res)
                //if its done
            });
        });
    });
    </script>
<?php endif; ?>

Please, feel free to contact if you any query. Thank You :)

I don't understand how u can count like in javascript only. Use wp_ajax_ACTION Hook to call your PHP functions, in your functions.php or in a plugin.

https://developer.wordpress/reference/files/wp-admin/admin-ajax.php/

add_action("wp_ajax_my_function", "my_function");

function my_function() {
 // Get parameters send by javascript xhr method

 // Do some stuff
}

add_action("wp_ajax_nopriv_my_function") for no user logged in.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>