WordPress.org

Ready to get started?Download WordPress

Forums

Correct Way to Disable Filters? (4 posts)

  1. Adam Capriola
    Member
    Posted 2 years ago #

    I'm working on a plugin and have come to a scenario where I am not sure what the "correct" route is to go here.

    Basically this code is part of an included php file of my plugin. I am filtering the content as per an option giving by the plugin. If the option is disabled, then I don't want to filter the content. Here's what I currently have:

    add_filter( 'the_content', 'pkmn_linker_standard', 8 );
    function pkmn_linker_standard($content) {
    	$linker_standard = pkmn_linker_get_setting('linker_standard'); // custom function, gets user's setting with get_option
            // if we're on a post and setting is enabled, do stuff
    	if ( is_singular('post') && !empty($linker_standard) ) {
    		// yada yada, does stuff
            }
    	return $content;
    }

    This works all well and good. However, I was wondering if it would be better to instead of checking if the setting is enabled within the function, to check if the function is enabled outside of the function, and if it's disabled, to remove the filter. So something like this instead:

    add_filter( 'the_content', 'pkmn_linker_standard', 8 );
    $linker_standard = pkmn_linker_get_setting('linker_standard'); // custom function, gets user's setting with get_option
    // If setting is disabled, remove filter
    if (  empty($linker_standard) ) {
           remove_filter( 'the_content', 'pkmn_linker_standard', 8 );
    }
    function pkmn_linker_standard($content) {
            // if we're on a post and setting is enabled, do stuff
    	if ( is_singular('post') ) {
    		// yada yada, does stuff
            }
    	return $content;
    }

    I guess my thinking is that it's better to not run the filter (efficiency-wise) at all than to run it and have it not do anything. Does this make sense? Is one approach better than the other?

  2. I'm not sure if it's more efficient or better one way or the other but, why not just check before adding the filter?

    if (  !empty($linker_standard) ) {
           add_filter( 'the_content', 'pkmn_linker_standard', 8 );
    }

    Instead of adding then deciding to removing it?

  3. Adam Capriola
    Member
    Posted 2 years ago #

    Good point. Yeah that makes more sense. Still, I'm not sure what's the "right" way to do it, you know? Like make the filter non-existent (either by removing it or not creating it like you suggested), or have the filter but make it do nothing.

  4. Jupiter_Dev
    Member
    Posted 2 years ago #

    Okay, i think what you can do is use a switch stattement, or set the filter as a variable, then use an if...else, but I am still learning myself. Also, here is a good WP Dev tutorial that deals with adding a filter:
    I hope it helps!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.