Passing along the package context in the page

Hello,

I wanted to pass along the context of the packages to my pages, so I could add some extra features is current user has ‘subscribed’ to such or such package.
I saw there was a need for that, in the forum, here and there but no solution provided.

So here it is @mry_darling, @majesticnationinfo

function add_custom_body_class_for_package($classes) {
	// Get current user 
	$current_user = wp_get_current_user();
	global $wpdb;
	
	//get package name (if any) for given user connected (user_id)
	$query = $wpdb->prepare(
		"
		SELECT 
			p.post_name
		FROM 
			{$wpdb->posts} AS p
		INNER JOIN 
			{$wpdb->postmeta} AS m ON m.post_id = p.ID
		INNER JOIN 
			{$wpdb->usermeta} AS um ON um.meta_key = m.meta_key
		WHERE 
			p.post_type = 'hp_listing_package' 
			AND um.meta_key = '_transient_hp_models/user_listing_package/version' 
			AND um.user_id = %d
		",
		$current_user->ID
	);

	// Execute the query
	$results = $wpdb->get_results($query);

	// Check and output results
	if (!empty($results)) {
		foreach ($results as $result) {
			$classes[] = $result->post_name; //add package name to body classes 
		}
	}else{
			$classes[] ='no-package'; //not needed, but nice to have		
	}    
    return $classes;
}
add_filter('body_class', 'add_custom_body_class_for_package');

This snippet will add the package names (slugs) to the <body> element.
Ex :
<body class=“… package free package-premium”>
or
<body class=“… no-package”>
if the user has not subscribed to anything (but is logged in)

Then you could use some CSS like so :

/* hide the button by default */
.my-premium-button, 
{
display:none;
} 

/* show for premium users only */
.package-premium .my-premium-button{
display:block;
} 

Of course, you would have to change package-free and package-premium to the name of your respective package slugs.

It’s not foolproof : user can still have access to the next page, or view the link in the source, modify the CSS locally to have the button to show if he gets really inquisitive, but fair enough.

Yep, that’s how I spent my time on new year’s eve.
Gotta do something, to not feel too lonely.

Happy new year !

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.