How can I show WP enqueued script or style in a custom section of the code? (Aside from the header and footer)

415 Views Asked by At

I'm working on a custom theme and for a specific reason am not using the get_header() function.

I enqueue scripts and styles with wp_enqueue_script and wp_enqueue_style, repectively and can get it to work if I call the get_header() function. No problem there.

The thing is that I'm customizing my header and get_header() adds code I don't need. How can I get the enqueued scripts and styles to show up somewhere that's not in the header or footer that appear with get_header() or get_footer()?

For example:

<head>
    <title>This is the title</title>
    <!-- scripts
     ================ -->
     SHOW ENQUEUED SCRIPTS HERE

    <!-- styles
     ================ -->
     SHOW ENQUEUED STYLES HERE
</head>

1

There are 1 best solutions below

0
On

I was able to figure it out, so I'll post the answer because I didn't see anything relevant in Google.

There's a hook called wp_print_footer_scripts

If you add the following line of code, you can get your scripts and styles to show up where you wrote the snippet:

do_action( 'wp_print_footer_scripts', '_wp_footer_scripts' );

If you want to split the styles from the scripts, you can use the two functions that are used in the _wp_footer_scripts callback function:

print_late_styles();

print_footer_scripts();

So, the example code shown in the question would end up like this:

<head>
    <title>This is the title</title>
    <!-- scripts
     ================ -->
     <?php print_footer_scripts(); ?>

    <!-- styles
     ================ -->
     <?php print_late_styles(); ?>
</head>

or just using the hook:

<head>
    <title>This is the title</title>
    <!-- scripts and styles
     ================ -->
    <?php do_action( 'wp_print_footer_scripts', '_wp_footer_scripts' ); ?>
</head>