Created
June 25, 2020 19:22
-
-
Save kimcoleman/0801b181f5d5bd9bf41053eef43543fc to your computer and use it in GitHub Desktop.
Restricts content for the 'my_pods_item' CPT by category.
This file contains hidden or 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 | |
/** | |
* Restricts content for the 'my_pods_item' CPT by category. | |
* If a CPT has a category restricted by a membership, then run restricton code | |
* Please adjust the filter name to be 'pmpro_has_membership_access_filter_<<cpt_name>>' | |
* | |
* You can add this recipe to your site by creating a custom plugin | |
* or using the Code Snippets plugin available for free in the WordPress repository. | |
* Read this companion article for step-by-step directions on either method. | |
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
*/ | |
function my_restrict_my_pods_item_categories( $hasaccess, $post, $user, $post_membership_levels ) { | |
global $wpdb; | |
if ( ! $hasaccess ) { | |
return $hasaccess; | |
} | |
$post_categories = wp_get_post_categories( $post->ID ); | |
if ( ! empty( $post_categories ) ) { | |
$sqlQuery = "(SELECT m.id, m.name FROM $wpdb->pmpro_memberships_categories mc LEFT JOIN $wpdb->pmpro_membership_levels m ON mc.membership_id = m.id WHERE mc.category_id IN(" . implode(",", $post_categories) . ") AND m.id IS NOT NULL) UNION (SELECT m.id, m.name FROM $wpdb->pmpro_memberships_pages mp LEFT JOIN $wpdb->pmpro_membership_levels m ON mp.membership_id = m.id WHERE mp.page_id = '" . $post->ID . "')"; | |
$results = $wpdb->get_results( $sqlQuery ); | |
if ( ! $results ) { | |
$hasaccess = true; | |
} | |
// if the user isn't logged-in, restrict content. | |
if ( !is_user_logged_in() ) { | |
$hasaccess = false; | |
} | |
$required_levels = array(); | |
foreach ( $results as $level ) { | |
$required_levels[] = $level->id; | |
} | |
if ( ! empty( $user ) ) { | |
$user_levels = pmpro_getMembershipLevelsForUser($user->ID); | |
$my_levels = array(); | |
foreach($user_levels as $curlevel) { | |
$my_levels[] = $curlevel->id; | |
} | |
if( count( array_intersect( $my_levels, $required_levels ) ) > 0 ) { | |
//the users membership id is one that will grant access | |
$hasaccess = true; | |
} else { | |
//user isn't a member of a level with access | |
$hasaccess = false; | |
} | |
} | |
} | |
return $hasaccess; | |
} | |
add_filter( 'pmpro_has_membership_access_filter_qpm_form', 'my_restrict_my_pods_item_categories', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment