Step-by-step:
If you put everything in your functions.php
or plugin file, it should work just fine.
-
We need a user meta field, where User can decide if they want to activate a certain CPT.
add_action( 'show_user_profile', 'my_user_meta_show_faq' ); add_action( 'edit_user_profile', 'my_user_meta_show_faq' ); add_action( 'user_new_form', 'my_user_meta_show_faq' ); function my_user_meta_show_faq( $user ) { $show_faq = get_user_meta($user->ID, 'show_faq', true); ?> <h3>Show FAQs?</h3> <?php _e('Yes', 'my_textdomain');?> <input type="radio" name="show_faq" value="yes" <?php checked('yes', $show_faq); ?> /><br /> <?php _e('No', 'my_textdomain');?> <input type="radio" name="show_faq" value="no" <?php checked('no', $show_faq); ?> /><br /> <?php } add_action( 'personal_options_update', 'my_user_meta_save' ); add_action( 'edit_user_profile_update', 'my_user_meta_save' ); function my_user_meta_save( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return; if($_POST['show_faq'] === 'yes') { update_user_meta($user_id, 'show_faq', 'yes'); } else { delete_user_meta($user_id, 'show_faq'); } }
-
We need to query that option on WP init. If that option is true we register our CPT.
add_action( 'init', 'my_cpt_init' ); function my_cpt_init() { if ( !is_user_logged_in() ) return; $current_user = wp_get_current_user(); $show_faq = get_user_meta($current_user->ID, 'show_faq', true); if($show_faq === 'yes') { register_post_type( 'faq', array( 'labels' => array( 'name' => __( 'Faq' ), 'singular_name' => __( 'Faq' ) ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'faq'), 'publicly_queryable' => true, 'supports' => array( 'title', 'editor' ) )); } }
Now we can toggle the CPT with our state of the user meta field.