Search code examples
phpwordpressshortcode

Registering shortcode in activation hook not working


I have been working on a plug-in and I have been trying to add a shortcode inside of a function that is registered as an activation hook. I know the function is being called, because if I add an echo statement inside of the function, WordPress will complain about receiving input after the header has been sent, but the shortcode does not display. However, if I move the add_shortcode outside of the function, then everything works fine.

Any ideas on what is going wrong?

This works:

<?php
/*
Plugin Name: Testing
*/

function short_code($atts) {
    return "This is a test";
}

function activate() {
    add_shortcode('testing', 'short_code');
}

//register_activation_hook(__FILE__, 'activate');
add_shortcode('testing', 'short_code');

This Doesn't:

<?php
/*
Plugin Name: Testing
*/

function short_code($atts) {
    return "This is a test";
}

function activate() {
    add_shortcode('testing', 'short_code');
}

register_activation_hook(__FILE__, 'activate');
//add_shortcode('testing', 'short_code');

Solution

  • register_activation_hook only fires once - when the plugin is activated. So your shortcode is only being registered that one time upon activation and is then no longer available.

    You should use add_shortcode as you have it in the first example. add_shortcode is itself a hook, it doesn't need to be inside another hook.