• Hello, I want to add caps on theme activation.

    I try this (the second) but it doesn’t recognize the activation and removes caps anyway.

    My function:

    function add_theme_caps()
    {
    	global $pagenow;
    	$role = get_role('administrator');
    	
    	if ('themes.php' == $pagenow && isset($_GET['activated'])) { // Test if theme is active
    		$caps = array(
    			'activate_plugins',
    		);
    		foreach ($caps as $cap) {
    			$role->add_cap($cap);
    		}
    	} else {
    		$caps = array(
    			'activate_plugins',
    		);
    		foreach ($caps as $cap) {
    			$role->remove_cap($cap);
    		}
    	}
    }
    add_action('load-themes.php', 'add_theme_caps');

    Can you help me?
    Thanks.

    PS: my original issue is about adding cpt custom caps

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    The problem with example code is they often don’t do anything useful. The example adds the cap OK, but then removes it any time themes.php admin screen is loaded afterwards (the else condition). The else condition would need to somehow check that one is actually switching from the theme with this code and not just looking. Since this code goes away with the theme, I’m not sure that’s feasible.

    I think the “switch_theme” action would have more promise. At least to remove the cap. You still might still need the activation part of your code to add the code. I’m not sure with “switch_theme” if the new theme’s code executes on activation or not.

    FWIW, adding a CPT from a theme is not recommended as it locks users to that theme. CPTs are best added from a plugin so users can freely switch themes. Plugins have dedicated ways to execute code on activation and deactivation from which you can reliably add or remove caps.

Viewing 1 replies (of 1 total)
  • The topic ‘Add caps on theme activation’ is closed to new replies.