1

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?

1 Answer 1

1

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') );
}
6
  • This works and seems much cleaner than the way I was trying to do it. Thank you!
    – Nexus6
    Jan 29, 2019 at 10:22
  • @Nexus6 yeah, I think it is a much nicer approach to this problem. Jan 29, 2019 at 10:22
  • Constants cannot be re-defined once they are defined. If they could, they wouldn't be 'constant'. (And note that code with a constant in a double-quote string will not be evaluated. All constants in strings must be single-quoted.) Jan 29, 2019 at 18:47
  • @RickHellewell Are you sure you're commenting the correct answer? There are no constants used in my answer ;) Jan 29, 2019 at 18:48
  • 1
    @KrzysiekDróżdż my comment was to the OP; it didn't seem like my comment was an 'answer'. Although I suppose it could be. I just wanted to put the statement (that constants cannot be redefined) for others as a learning thing. And the thing about double quotes is something that I was struggling with just today. I have no issue with your answer. Jan 29, 2019 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.