Define a wordpress constant through plugin functions?

I'm working on a plugin and trying to build in an option to disable post revisions. I have the setting registered, and confirmed that the checkbox is linking to the database. The option value is either null or 1.

What I want to do is define this constant: define('WP_POST_REVISIONS', false); in the plugin file only if the option is set to 1.

If I put the constant directly into the plugin functions file it works, but if I try and use it in an if statement or through a function, it doesn't work, no matter how I try and do it.

I'm getting the option value like this: $disable_revisions = get_option('disable-revisions');

Here's what I've tried:

if ($disable_revisions==1){
    define('WP_POST_REVISIONS', false);
}

I also tried using a seperate function:

if ($disable_revisions==1){
    add_action('admin_init', 'disable_revs');
}

function disable_revs(){
    define('WP_POST_REVISIONS', false);
}

And I tried adding the action to 'wp', 'init' and a few others too, but none of them work.

How can I define the constant only if $disable_revisions = 1?

Topic revisions constants plugin-development options posts Wordpress

Category Web


I don’t think you should define constants in your plugin. It will be very hard to debug later on.

IMHO using wp_revisions_to_keep filter will be much nicer solution.

So your code could look like this:

add_filter( 'wp_revisions_to_keep', 'my_revisions_to_keep_based_on_settings', 10, 2 );

function my_revisions_to_keep_based_on_settings( $num, $post ) {
    // change that according to your needs
    return intval( get_option('disable-revisions') );
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.