Created
November 22, 2016 18:44
-
-
Save geilt/fad737fbdb1f422638985b6ed82fa4de to your computer and use it in GitHub Desktop.
Favorites System
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Create page in Wordpress called "Favorites" | |
// Access by calling /favorites?add_favorite=post_id, /favorites?remove_favorite=post_id | |
// in PHP this would be $link = '/favorites?add_favorite=' . get_the_ID(); | |
//page-favorites.php | |
if(is_user_logged_in()){ | |
$favorites = get_user_meta(get_current_user_id(), 'favorites', true); | |
if(!empty($_GET['add_favorite'])){ | |
if(empty($favorites)) $favorites = array(); | |
$key = array_search($_GET['add_favorite'], $favorites); | |
if($key === false){ | |
array_unshift($favorites, $_GET['add_favorite']); | |
update_user_meta(get_current_user_id(), 'favorites', $favorites); | |
} | |
} | |
if(!empty($_GET['remove_favorite'])){ | |
$key = array_search($_GET['remove_favorite'], $favorites); | |
if($key !== false){ | |
array_splice($favorites, $key); | |
update_user_meta(get_current_user_id(), 'favorites', $favorites); | |
} | |
} | |
echo json_encode($favorites); | |
} else { | |
http_response_code(400); | |
echo json_encode(array('err' => 'User not logged in')); | |
} | |
//Loop for Favorites. Put this in your template file | |
if(is_user_logged_in()){ | |
$favorites = get_user_meta(get_current_user_id(), 'favorites', true); | |
$favs = new WP_Query( | |
array( | |
'post_type' => 'post', | |
'post_status' > 'publish', | |
'posts_per_page' => -1, | |
'post__in' => $favorites | |
) | |
); | |
?> | |
<?php while($favs->have_posts()): $favs->the_post(); ?> | |
<?php the_title(); ?> | |
<?php the_content(); ?> | |
<?php endwhile; ?> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment