Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

WordPress Plugin to run on specific pages

Options
  • 18-04-2016 11:57am
    #1
    Registered Users Posts: 1


    I have developed a new WordPress plugin and I included a few CSS and JavaScript libraries in this.

    I have noticed that these includes are loaded onto all pages not just the pages I have included the short code for my plugin. This will clearly impact performance loading unnecessary scripts/styles.

    Is there a function within WordPress where you can set a condition on what pages a Wordpress plugin can run on?

    I am loading in the scripts/CSS like this within my php:

    function my_function() {
    wp_register_script( 'example', plugins_url('/scripts/example.js', __FILE__ ) );
    wp_register_style('example', plugins_url( '/example/example.css', __FILE__ ) );
    wp_enqueue_style('example);
    wp_enqueue_script('example');
    }

    add_action( 'wp_enqueue_scripts', 'my_function' );


Comments

  • Registered Users Posts: 7,739 ✭✭✭mneylon


    You'd need to dig around the Wordpress codex a bit:
    https://codex.wordpress.org/Writing_a_Plugin#Template_Tags


  • Registered Users Posts: 6,501 ✭✭✭daymobrew


    If you know the page ID, title or slug you can use is_page().


  • Registered Users Posts: 6,149 ✭✭✭Talisman


    For including JavaScript for a plugin I usually add a hook to the function which handles the shortcode.
    function lets_do_example_shortcode( $atts ) {
      ...
      // add hook for loading scripts
      do_action( 'lets_do_example_hook' );
    }
    
    // register function for hook
    add_action( 'lets_do_example_hook', 'include_my_scripts' );
    
    function include_my_scripts() {
      wp_register_script( 'jquery-tooltipster', PLUGIN_URL."js/jquery.tooltipster.min.js", array('jquery'), null, true );
      // register the plugin JavaScript file
      wp_register_script( 'my-plugin-js', PLUGIN_URL."js/my-plugin.js", array('jquery','jquery-ui','jquery-tooltipster'), null, true );
      // add the JavaScript file to the page footer
      wp_enqueue_script( 'my-plugin-js', null, true );
    }
    

    You can use the same technique to inline CSS code.


Advertisement