0

I am using the following code and I can't see anything in the footer of my site on the front end where the wp_footer function is called. It does, however, appear before the opening <!DOCTYPE html> in the admin area.

function xyz_footer_print() {
    echo 'footer script here';
}
add_action( 'wp_footer', xyz_footer_print() );

2 Answers 2

3

That's because you're not using add_action correctly, what you've written is functionally the same as this:

function xyz_footer_print() {
    echo 'footer script here';
}
$value = xyz_footer_print();
add_action( 'wp_footer', $value );

xyz_footer_print() immediately runs the function and returns nothing. As a result your add_action call says that on the wp_footer even, do nothing.

So you actually have 2 problems not 1, and if you check your PHP error log or install a tool such as query monitor/debug bar you'd see the warning/notice.

Instead actions always take the form:

add_action( 'action name', 'callable type value, aka the name of function to run when the action happens' );

That should give you enough information to fix this, but, it's the wrong way to put javascript in your footer. You should instead use a JS file and enqueue it the way webelaine suggested.

1
  • Yeah, I managed to work that out and then forgot to update here! Cheers.
    – Badger
    Commented Nov 25, 2022 at 20:43
2

What's happening here is your echo is executing before anything else.

Try using the wp_enqueue_scripts hook instead of wp_footer, and instead of echo you will wp_enqueue_script().

<?php
// Using a different hook:
add_action( 'wp_enqueue_scripts', 'wpse_411187_script' );

function wpse_411187_script() {
    wp_enqueue_script(
        // "Handle" - a unique name for your script
        'xyz-footer-print',
        // Path to the JS file - adjust as needed
        plugins_url( 'build/xyz-footer-print.js', dirname( __DIR__ ) ),
        // Array of dependencies
        '',
        // Version number
        '1.0',
        // True to place the script the footer
        true
    );
}
?>
1
  • Thanks, I would normally enqueue, but no access to ftp.
    – Badger
    Commented Nov 25, 2022 at 21:02

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.