Created
June 25, 2020 19:09
-
-
Save kimcoleman/560eabe25dcc677fef3af32d489333d7 to your computer and use it in GitHub Desktop.
Restricts content based on a CPT post's 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 based on a CPT post's 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_qpm_form_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_qpm_form_categories', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment