Favourite button short code

Home » Snippets » Favourite button short code
0

Created with:

Visibility: 

public

Creator: Mirriah

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
/**
 * Template for displaying the favourite button on the Field Trips custom post type.
 *
 * @package YourTheme
 */

// Register the shortcode
add_shortcode('wpturbo_favorite_button', 'wpturbo_favorite_button_shortcode');

// Callback function for the shortcode
function wpturbo_favorite_button_shortcode($atts) {
    // Get the current post ID
    $post_id = get_the_ID();

    // Get the current user ID
    $user_id = get_current_user_id();

    // Check if the current user has already favorited this post
    $is_favorited = wpturbo_is_post_favorited($post_id, $user_id);

    // Output the favourite button
    if ($is_favorited) {
        // Display the unfavorite button
        $button_html = '<a href="#" class="favorite-button favorited"><i class="fas fa-heart"></i></a>';
    } else {
        // Display the favorite button
        $button_html = '<a href="#" class="favorite-button"><i class="far fa-heart"></i></a>';
    }

    // Return the button HTML
    return $button_html;
}
				

Explanation:

In this updated code, we first register the shortcode wpturbo_favorite_button using the add_shortcode() function. The first parameter is the shortcode name, and the second parameter is the callback function that will be executed when the shortcode is used in a post.

Then, we define the wpturbo_favorite_button_shortcode function as the callback for the shortcode. Inside this function, we retrieve the current post ID and user ID, just like before.

We then check if the post is favorited and generate the HTML for the favorite button accordingly. The HTML is stored in the $button_html variable.

Finally, we return the $button_html variable, which will be replaced with the shortcode output when the shortcode is used in a post.

To use the shortcode in your post's design layout, you can simply add [wpturbo_favorite_button] wherever you want the favorite button to appear.

Register an account to save your snippets or go Pro to get more features.