Site icon Anthony Carbon

How to add like button in media gallery item using Buddypress and rtMedia WordPress plugin?

Hi guys !!! How to add like button in media gallery item using Buddypress and rtMedia WordPress plugin? Please follow the steps below.

Step 1:

Override the “media-gallery-item.php” in your WordPress theme.

wp-content/themes/mytheme-folder-name/rtmedia/media/media-gallery-item.php
Step 2:

Place the code anywhere inside of your “li” tag.

<?php wdes_rtmedia_like( rtmedia_id(), bp_loggedin_user_id() ); ?>
Step 3:

Paste this code to your functions.php.

function wdes_rtmedia_like( $media_id, $user_id = false ){
	ob_start();
	global $bp;
	$main_class = new RTMediaLike;
	$label = __( 'Like', 'buddypress-media' );
	$class = '';
	if( $main_class->is_liked( $media_id, $user_id ) && $user_id ){
		$label = __( 'Unlike', 'buddypress-media' );
		$class = ' unlike';
	}
	if ( ! is_user_logged_in() ) { return; }
	?>
	<span id="media-like-<?php echo $media_id; ?>" class="wdes-rtmedia-like">
    <form action="<?php echo trailingslashit( get_rtmedia_permalink( $media_id ) ); ?>like/">
    <button type="submit" id="rtmedia-like-button-<?php echo $media_id; ?>" class="wdes-like-btn <?php echo $class; ?>"><span><?php echo $label; ?></span></button>
	<?php wp_nonce_field( 'rtm_media_like_nonce' . $media_id, 'rtm_media_like_nonce', true, true ); ?>
    </form>
    </span>
    <?php
	echo ob_get_clean();
}
Step 4:

Paste this code to your .js file. If you don’t have one, please create.

jQuery( document ).ready( function( $ ){  
	if( $( 'span.wdes-rtmedia-like' ).length ){
		$( document ).on( 'click', '.wdes-like-btn', function( e ) {
			e.preventDefault();
			var that = this;
			var like_nonce = $( this ).siblings( '#rtm_media_like_nonce' ).val();
			rtmedia_like = $( this ).attr( 'id' );
			$( this ).attr( 'disabled', 'disabled' );
			var url = $( this ).parent().attr( 'action' );
			$( that ).prepend( '<img class=\'rtm-like-loading\' src=\'' + rMedia_loading_file + '\' style=\'width:10px\' />' );
			$.ajax( {
				url: url,
				type: 'post',
				data: { json: true, like_nonce: like_nonce },
				success: function( data ) {
					try {
						data = JSON.parse( data );
					} catch ( e ) {
	
					}
					$( '#' + rtmedia_like + ' span' ).html( data.next );
					if( data.next == 'Unlike' ){
						$( '#' + rtmedia_like ).addClass( 'unlike' );
					}else{
						$( '#' + rtmedia_like ).removeClass( 'unlike' );
					}
					$( '.rtm-like-loading' ).remove();
					$( that ).removeAttr( 'disabled' );
				}
			});
		});
	}
});

You have now the Like / Unlike button. Happy coding 🙂

Exit mobile version