• Resolved martijnrammeloo

    (@martijnrammeloo)


    Hi, is it possible to change the ‘content permissions’ of specific posts via code (or, a shortcode)?

    Use case: suppose I want to add or remove a certain role in a function without any admin interference.

    Cheers, Martijn

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Support Omar ElHawary

    (@omarelhawary)

    Hi @martijnrammeloo,

    Thanks for reaching out Members Support Team!

    Yes, this is possible via code when using the Members (Membership & User Role Editor) plugin.

    Members exposes helper functions that let you programmatically manage a post’s Content Permissions (the same ones set in the editor UI), so you can add or remove roles without admin interaction.Examples

    Add a role to a specific post

    members_add_post_role( $post_id, 'subscriber' );

    Remove a role

    members_remove_post_role( $post_id, 'subscriber' );

    Replace all roles

    members_set_post_roles( $post_id, array( 'subscriber', 'editor' ) );

    Automating it (example)

    If you want this to happen automatically when a post is published, it’s best to hook into the post status transition:

    add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
    if ( 'publish' !== $new_status || 'publish' === $old_status ) {
    return;
    }

    if ( wp_is_post_revision( $post->ID ) || wp_is_post_autosave( $post->ID ) ) {
    return;
    }

    members_add_post_role( $post->ID, 'subscriber' );
    }, 10, 3 );

    These functions directly update the same metadata that Members uses for Content Permissions in the editor, so the changes will be reflected there as well.

    Just make sure the Members plugin is active before calling them (e.g. function_exists() check).

    Hope that helps!

    Thread Starter martijnrammeloo

    (@martijnrammeloo)

    Thanks a lot, I have some homework to do 🙂

Viewing 2 replies - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.