[wp-hackers] Like Posts - Store Data in DB, User_Meta or Post_Meta

Xavier Faraudo i Gener wordpress at web-warlocks.net
Tue Nov 12 05:13:15 UTC 2013


El 11/11/2013 19:01, BenderisGreat ha escrit:
> What would be the best option for storing which posts a user likes?  They
> click a like button, and it can be stored in the post_meta, or the
> user_meta, or a sep db table.  It seems to be that storing in the post_meta
> would make the most sense, but I wanted to ask before moving ahead.
>

I'd seriously consider using neither of those, but an option. (Pun not 
intended. I mean "I'd seriously consider using the wp_options table and 
API".) At least for starters, until it's clear which kind of queries are 
you going to run (and have a solid API).

Dilemma here would be if the keys for the option should be post ID or 
user ID... But you can always hook at an early stage and add to cache 
the "inverted"/"mirrored" data. F.i., if you have it stored in the form 
user_id => array of post ids (with an option name like 
"posts_liked_by_user_id"), you can add the array of post_id => array of 
liking user_ids to cache. This way, you ensure data integrity much 
better than by storing it in two places, and with no added queries. (And 
you can copy the very option to cache, too, so you can access the data 
consistently with wp_cache_get, instead of having to remember which one 
was by get_option and which one by wp_cache_get.)

So, for instance (I'm not quite sure I've explained myself well), your 
function could be something like:

function already_liked_check() {
	global $post, $current_user;
	if ( ! $post = get_post( $post ) )
		return false; // not a valid post

	$post_ids_liked_by_user = (array) wp_cache_get( $current_user->ID, 
'posts_liked_by_user_id' );

	/* or also
	 * $all_posts_liked_by_user_id = get_option( 'posts_liked_by_user_id' );
	 * $post_ids_liked_by_user = isset( $all_posts_liked_by_user_id[ 
$current_user->ID ] ) ? $all_posts_liked_by_user_id[ $current_user->ID ] 
: array();
	 */

	if ( in_array( $post->ID, $post_ids_liked_by_user ) ) {
		// User likes the post
	} else {
		// User does not like the post
	}
}

Also, juggling with arrays alone you can also pull more-or-less easily 
things like:

·Other posts liked by this user
·Other users who liked this post
·Users who liked this post also liked…
·Users who like similar things to user (checking how many matching like 
posts both have)
·Most liked posts
·Most like-able users

… which makes for a nice basic set of features for a like-post addon.

-- 
Xavier Faraudo i Gener (the WordPress Web Warlock)


More information about the wp-hackers mailing list