Wp_enqueue_scripts executing outside wordpress post context?

In the acorn article about assets management, it mentions how to do asset management with an example of bundling a custom javascript file so it can be loaded on specific pages.

This is vanilla wordpress functionality using the wp_enqueue_scripts hook. In sage 10, this hook is setup in app/setup.php of your theme.

None of the methods that typically work in this function are returning expected values. For example, when I hit a page that’s a custom post type, get_post_type() return empty. Also, get_page_template() always returns empty.

Essentially I have no way of loading different bundles depending on the page I’m on. I don’t see how the example in the documentation can actually work. It makes sense in theory, but it’s not what I’m experiencing.

Please post the actual code that you’re trying to get working / give us steps to reproduce

Sure. In app/setup.php of any sage 10 theme, modify the wp_enque_scripts hook to add the following log entry:

add_action('wp_enqueue_scripts', function () {
    error_log('Post type is: ' . get_post_type() . ' and template is: ' . get_page_template());
    bundle('app')->enqueue();
}, 100);

Then make sure you’ve got logging enabled. You’ll see nothing for the post type or page template in the logs when you hit any page.

Your code runs correctly for me:

[01-Aug-2023 08:53:28 UTC] Post type is: page and template is: /app/web/wp/wp-includes/template-canvas.php

Are you able to provide a more complete example?

1 Like

Crap. OK so it is something on my end. It’s a pretty extensive project with a lot of service providers that hook wordpress so I’ll have to go through and see if I can isolate some code to share with more of what may be going on. I really don’t know where to start, so I may just find it in the process.

Thanks for confirming it does work as intended out of the box!

@talss89 hold on, looking at your output that’s not a blade file in a sage theme?

Sorry - I ran the snippet on a theme which makes use of full site editing / block editor.

Here’s output from a non-FSE Sage 10 vanilla installation - still works:

[01-Aug-2023 18:18:02 UTC] Post type is: post and template is: /app/web/app/themes/sage-test/resources/views/page.blade.php

@talss89 thanks. Just making sure :slight_smile: Appreciate you confirming it! I’ll do some more investigating! Hopefully if I can figure out what it is I can find a way to help other people not run into whatever’s going on…

OK first thing I’ve figured out. If I hit the site using the base URL specified in bud.config.js then get_post_type() works. However if I hit the site using the proxy URL (the backend URL for wordpress), it returns empty. Strange, I hope it doesn’t do that in production but I’m guessing not. I’ll find out when I deploy it to staging.

As for get_template_path(), it’s still returning a blank string no matter what. Still looking into it.