Last active
November 7, 2021 03:59
-
-
Save sc0ttkclark/5c2d6e1a4a000dcdfcf1ec9db18bf744 to your computer and use it in GitHub Desktop.
Integrate with WPGraphQL to check if the current user has access to certain post types.
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 | |
/** | |
* Integrate with WPGraphQL to check if the current user has access to certain post types. | |
* | |
* 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_pmpro_wpgraphql_data_is_private( $is_private, $model_name, $data ) { | |
// Bypass if the object is already private. | |
if ( ! $is_private ) { | |
return $is_private; | |
} | |
// Confirm PMPro is available. | |
if ( ! function_exists( 'pmpro_has_membership_access' ) ) { | |
return $is_private; | |
} | |
// Check which models we want to support. | |
if ( $model_name !== 'PostObject' ) { | |
return $is_private; | |
} | |
// Default supported post types. | |
$supported_post_types = [ | |
'post' => true, | |
'page' => true, | |
]; | |
// Check for custom post type support. | |
if ( function_exists( 'pmprocpt_getCPTs' ) ) { | |
$pmpro_cpts = pmprocpt_getCPTs(); | |
foreach ( $pmpro_cpts as $cpt ) { | |
$supported_post_types[ $cpt ] = true; | |
} | |
} | |
// Only run access checks for supported post types. | |
if ( ! isset( $supported_post_types[ $data->post_type ] ) ) { | |
return $is_private; | |
} | |
return pmpro_has_membership_access( $data->ID ); | |
} | |
add_filter( 'graphql_data_is_private', 'my_pmpro_wpgraphql_data_is_private', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment