post-count.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* jshint onevar: false, smarttabs: true */
  2. var wpPostLikeCount = wpPostLikeCount || {};
  3. (function($) {
  4. wpPostLikeCount = jQuery.extend( wpPostLikeCount, {
  5. jsonAPIbase: 'https://public-api.wordpress.com/rest/v1',
  6. APIqueue: [],
  7. wpPostLikeCount: function() {
  8. $( '.post-like-count' ).each( function() {
  9. var post_id = $(this).attr( 'data-post-id' );
  10. var blog_id = $(this).attr( 'data-blog-id' );
  11. wpPostLikeCount.APIqueue.push( '/sites/' + blog_id + '/posts/' + post_id + '/likes' );
  12. } );
  13. wpPostLikeCount.getCounts();
  14. },
  15. showCount: function( post_id, count ) {
  16. if ( count > 0 ) {
  17. $( '#post-like-count-' + post_id ).find( '.comment-count' ).hide();
  18. $( '#post-like-count-' + post_id ).find( '.comment-count' ).text( count );
  19. $( '#post-like-count-' + post_id ).find( '.comment-count' ).fadeIn();
  20. }
  21. },
  22. getCounts: function() {
  23. var batchRequest = {
  24. path: '/batch',
  25. data: '',
  26. success: function( response ) {
  27. for ( var path in response ) {
  28. if ( ! response[path].error_data ) {
  29. var urlPieces = path.split( '/' ); // pieces[4] = post id;
  30. var post_id = urlPieces[4];
  31. wpPostLikeCount.showCount( post_id, response[path].found );
  32. }
  33. }
  34. },
  35. error: function( /*response*/ ) {
  36. }
  37. };
  38. var amp = '';
  39. for( var i = 0; i < wpPostLikeCount.APIqueue.length; i++ ) {
  40. if ( i > 0 ) {
  41. amp = '&';
  42. }
  43. batchRequest.data += amp + 'urls[]=' + wpPostLikeCount.APIqueue[i];
  44. }
  45. wpPostLikeCount.request( batchRequest );
  46. }
  47. } );
  48. })(jQuery);
  49. jQuery(document).ready(function(/*$*/) {
  50. wpPostLikeCount.wpPostLikeCount();
  51. });