Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travislima/7ee29663a52a9f15bf4c6145236dd1e9 to your computer and use it in GitHub Desktop.
Save travislima/7ee29663a52a9f15bf4c6145236dd1e9 to your computer and use it in GitHub Desktop.
<?php
/**
* Bulk assign membership levels to posts and pages.
* You will need to adjust the $levels to your desired levels as well as select your desired $post_type.
* Onced added to your site add the following to the end of yout URL in order ro run the script `/wp-admin/?assign_levels_posts=true`
* Add this code to your Customizations Plugin/Code Snippets by following this guide - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function mypmpro_bulk_assign_levels_to_posts(){
if( isset( $_REQUEST['assign_levels_posts'] ) ){
global $wpdb;
$levels = array( 1, 2 ); //Assign these levels to each post
$post_type = 'post'; //Change to your preference
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ){
while( $the_query->have_posts() ){
$the_query->the_post();
$post_id = get_the_ID();
//remove all memberships for this page
$wpdb->query("DELETE FROM {$wpdb->pmpro_memberships_pages} WHERE page_id = '$post_id'");
//add new memberships for this page
if(is_array($levels))
{
foreach($levels as $level){
$sql = "INSERT INTO {$wpdb->pmpro_memberships_pages} (membership_id, page_id) VALUES('" . intval($level) . "', '" . intval($post_id) . "')";
echo $sql."<br/>";
$wpdb->query($sql);
}
}
}
} else {
echo "Nothing Found";
}
exit();
}
}
add_action( 'admin_init', 'mypmpro_bulk_assign_levels_to_posts' );
@laurenhagan0306
Copy link

This recipe is included in the blog post on "Bulk methods to restrict access to posts, pages, and CPTs for a specific membership level ID via MySQL" at Paid Memberships Pro here: https://www.paidmembershipspro.com/bulk-methods-to-restrict-access-to-posts-pages-and-cpts-for-a-specific-membership-level-id-via-mysql/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment