0

I'm working with a custom page template in Genesis and need to remove the post content and replace it when a certain condition is set. That part is working fine, but I also need to display information from a variable in the new content.

It seems simple, but something isn't working, and I think it's that I don't understand how to pass a variable into a function correctly. I'm assuming that a variable assigned outside of a function will be available in the function. Here's my template:

//* Template Name: Notification Template

$notice ="ALERT!"; //This will be set dynamically from code above, but I'll keep it simple for now. 

if($notice){

        //echo $notice ; // If I echo here, it displays at the top of the page.

        remove_action( 'genesis_entry_content', 'genesis_do_post_content' );

        add_action ( 'genesis_entry_content', 'do_custom_content', 5 );

        function do_custom_content(){                           

            echo $notice; // This is not displaying anything!
            echo 'Test Output'; //This text does display

        }
    }

When I echo the $notice in the do_custom_content() function, nothing is happening. So, it is probably that I don't understand how the php is working, since $notice is not passing through into the do_custom_content() function.

1

If you are going to be setting the notice dynamically, what I would do is just pull in the notice in the callback function. But if you can't do that for whatever reason, you can do a little wizardry like so:

if( $notice ) {

    remove_action( 'genesis_entry_content', 'genesis_do_post_content' );

    add_action ( 'genesis_entry_content', function() use ($notice) {
        echo $notice;
    }, 5 );

}

This takes advantage of the php use keyword available to anonymous functions.

  • Nice! The notice isn't available as a callback, though I could probably also rewrite it to be, but the 'use' keyword is something new to me. – AJD Jul 11 '17 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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