0

When a new Wordpress post is being created using post category "A" (or "B" or "C"), I need to automatically check the Woocommerce-Memberships Disable restrictions checkbox with a PHP hook. This will allow all viewers unrestricted access to view the post.

checkbox picture[1]

I have tried adding an action to the "save_post" hook to add the "_wc_memberships_force_public" value of "yes" to the {wp_prefix}_post_meta table and the checkbox will show as checked because of this, however, when viewing the post it is still restricted. When I remove the action (by commenting it out from my functions.php file) and check the Disable restrictions checkbox manually before saving the post, the post can be viewed without restriction (as expected).

add_action( 'save_post', 'action_save_post_force_public', 99, 3);

function action_save_post_force_public($post_id, $post, $is_update){
         $already_forced = get_post_meta( $post_id, '_wc_memberships_force_public', $single=true );
         if ( 'yes' === $already_forced ){ return; }

         $categories = get_the_category( $post_id );

         if ( empty( $categories ) ){ return; }

         $force_public_slugs = array('A', 'B', 'C');

         foreach ( $categories as $term ){
             if ( in_array( $term->slug, $force_public_slugs ) ){
                 update_post_meta( $post_id, '_wc_memberships_force_public', 'yes' );
                 break;
             }
         }
}

I expect all viewers to have unrestricted access to view the post content whether this box is checked automatically or manually. Instead it only works when manually checking the box.

ztron
  • 1
  • 1

1 Answers1

0

Instead of using update_post_meta( $post_id, '_wc_memberships_force_public', 'yes' );, try this:

// Disable post restrictions (Woocommerce Membership)
$wc_membership = \WC_Memberships::instance();
$wc_membership->get_restrictions_instance()->set_content_public($post);

It works well for me ;)

You can find an example of this piece of code in the file woocommerce-memberships/includes/admin/class-wc-memberships-admin.php