• Hello,

    I’m trying to find an answer what is the best way to close “if function_exist” with endif; before add_action or after? I saw many examples were closing can be in both places. Is there any difference?

    eg:

    if ( ! function_exists( 'tinyforge_content_width' ) ) :
    
    function tinyforge_content_width() {
    	if ( is_page_template( 'page-templates/full-width.php' ) || is_attachment() || ! is_active_sidebar( 'sidebar-1' ) ) {
    		global $content_width;
    		$content_width = 960;
    	}
    }
    add_action( 'template_redirect', 'tinyforge_content_width' );
    endif;

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Before. The call to add_action() must always be done after you’ve defined the function, never inside the function itself.

    As an example, this will work:

    function my_function () {
        // Do something here
    }
    add_action ('some_action', 'my_function');

    This example won’t work because the add_action() function call is never called:

    function my_function () {
        // Do something here
        add_action ('some_action', 'my_function');
    }

    Ahh.. %$&*. I spoke to soon… I should read the questions better!!!

    Using it as in your example, it could be done either way. It depends on how it’s going to be used.

    If you add it inside the if() block then your function will be linked only if it’s not set somewhere else, which may be a godo thing if you don’t want to over-ride some one elses function.

    If you add it outside the if() block, then the function will be added to that action even if it was before. I haven’t tried doing this myself, but I’d assume that would run the function twice for the same action, but it would also allow you to add it to a different action/actions for what you need it to do.

    Hopefully that makes a bit more sense to your problem then my first reply?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘What is the right way to close "if function_exist"?’ is closed to new replies.