Skip to main content
edited title
Link

after refresh the id that shows correct in first time click, changes to 1

Source Link

after refresh the id that shows correct in first time click changes

I made a like post type for another post type called recipe that user can toggle for like and getting back the like. I have to get the latest like id of specific single recipe when cliked on in data-like attr. first of all when user click to the heart button it passes true id and makes a new like post with the same id and if I click again on it; likes remove and remove the like post.

But if I refresh the page after like a recipe and whant to remove it , I can't! and when I use inspect for watching the ID that it must show on data-like it changes to 1. the js are correct as I know. I just share the query and the front codes of single-recipe.php if it helps. Thanks.

                <?php
while (have_posts()) {
    the_post();
            $likeCount = new WP_Query(array(
                'post_type' => 'like',
                'meta_query' => array(
                    array(
                        'key' => 'liked_recipe_ID',
                        'compare' => '=',
                        'value' => get_the_ID()
                    )
                )
            ));

            $exitStatus = 'no';
            // a query for if the user liked the current recipe make data-exist to yes
            if (is_user_logged_in()) {
                $existQuery = new WP_Query(array(
                    'author' => get_current_user_id(),
                    'post_type' => 'like',
                    'meta_query' => array(
                        array(
                            'key' => 'liked_recipe_ID',
                            'compare' => '=',
                            'value' => get_the_ID()
                        )
                    )
                ));
                if ($existQuery->found_posts) {
                    $exitStatus = 'yes';
                }
            }
            ?>
            <div class="like-box" data-like="<?php echo isset($existQuery->posts[0]->ID); ?>" data-exist="<?php echo $exitStatus; ?>" data-recipeID="<?php the_ID(); ?>">
                <span class="like-box__heart heart-hollow">
                    <img src="<?php echo get_theme_file_uri() ?>/assets/images/heart-hollow.svg" alt="">
                </span>
                <span class="like-box__heart heart-filled">
                    <img src="<?php echo get_theme_file_uri() ?>/assets/images/heart-filled.svg" alt="">
                </span>
                <span class="like-count"><?php echo $likeCount->found_posts; ?></span>
            </div>