Enqueue custom script or style when View is present

Support MB Views Enqueue custom script or style when View is presentResolved

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #35716
    JasonJason
    Participant

    How do I enqueue a script when the short code for a View is used in a page or post?

    #35721
    Long NguyenLong Nguyen
    Moderator

    Hi Jason,

    You can just add the CSS, JS code to the view editor to run it on a page/post when you insert the view shortcode. Screenshot https://monosnap.com/file/7fmXTsK6wCfTTRI6qsJthlm8lDp5yq

    #35734
    JasonJason
    Participant

    I know I can write my own customs CSS there. I want to enqueue assets that are already registered. This is common in WordPress plug-ins and themes.

    As you can see from this blog post, it is recommended as a best practice.
    https://www.wpbeginner.com/wp-tutorials/how-to-properly-add-javascripts-and-styles-in-wordpress/

    #35753
    Long NguyenLong Nguyen
    Moderator

    Hi,

    The view works as a template, not a function file so it's not possible to enqueue script with a view like that. You can use the <link> tag to load the script, style file in the Template tab.

    <link rel="stylesheet" href="mystyle.css">
    View content
    
    #35754
    JasonJason
    Participant

    It is possible to enqueue an asset when a short code is present in a post, as you can see in this example: https://developer.wordpress.org/reference/functions/has_shortcode/#comment-747

    There should be a way to enqueue some script when some post uses some shortcode.

    #35764
    Long NguyenLong Nguyen
    Moderator

    Hi,

    Thanks for sharing the documentation.

    Following that, the code would be

    function add_mbview_script() {
        global $post;
        if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'mbv') ) {
            wp_enqueue_script( 'my-script');
        }
    }
    add_action( 'wp_enqueue_scripts', 'add_mbview_script');
Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.