Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

WordPress Plugin to run on specific pages

  • 18-04-2016 11:57AM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 Posts: 7,742 ✭✭✭mneylon


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


  • Registered Users, Registered Users 2 Posts: 6,651 ✭✭✭daymobrew


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


  • Registered Users, Registered Users 2 Posts: 7,098 ✭✭✭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