I am working on my first WordPress plugin. The plugin basically creates a few short codes to achieve a few effects. In order to only include all of the css and js files on the pages where they are needed I have set my wp_enqueue_* function calls to be called if a short code is activated. That may not have been a very clear description so here are code snippets related to what I am talking about:

add_shortcode( 'slider_space', 'f_slider_space');

function link_page_files(){
        wp_enqueue_style( 'cccslider-style', plugins_url("...") );
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'jquery.easing', plugins_url("..."), array('jquery') );
        wp_enqueue_script( 'scrollcontrol', plugins_url("...") );
        wp_enqueue_script( 'cccslider', plugins_url("..."), array('jquery.easing', 'scrollcontrol') );

function f_slider_space($atts, $content = null){
// ..........

It seems to be working, but I am wondering if this is not best practice. What solution is best for controlling which pages the files are included in?

| improve this question | | | | |

That would print the stylesheet links into the footer. Works in most browsers, but is invalid HTML. You should hook into the action wp_head instead and check the post content for your shortcodes. Use a priority 0 to run earlier than the the action wp_enqueue_scripts.

add_action( 'wp_head', 'shortcode_check', 0 );

function shortcode_check() {
    global $wp_query;

    if ( empty ( $wp_query ) or empty ( $wp_query->posts ) )

    foreach ( $wp_query->posts as $post )
        if ( FALSE !== stripos( $post->post_content, '[shortcodename' ) )
            return add_action( 'wp_enqueue_scripts', 'shortcode_enqueue' );

function shortcode_enqueue() {
    // enqueue scripts and stylesheets here
| improve this answer | | | | |

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.