2
<?php

class OrdersShortcode {

    function __construct() {
        add_shortcode('order_ajax_form', array(&$this, 'order_ajax_form'));
    }

    function my_enqueued_assets()
    {
        wp_enqueue_script('my-script', "//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js");
        wp_enqueue_script('my-script2', plugin_dir_url(__FILE__) . 'js/easyResponsiveTabs.js');
        wp_enqueue_script('my-script3', plugin_dir_url(__FILE__) . 'js/fb.js');
        wp_enqueue_script('my-script4', plugin_dir_url(__FILE__) . 'js/verify.js');
        wp_enqueue_style('my-style', plugin_dir_url(__FILE__) . 'css/style.css');
        wp_enqueue_style('my-style2', plugin_dir_url(__FILE__) . 'css/easy-responsive-tabs.css');
    }

    function order_ajax_form() {
        add_action('wp_enqueue_scripts', array( $this, 'my_enqueued_assets'));

        include(dirname(dirname(__FILE__)) . '/views/form.php');
    }
}

I am trying to use wp_enqueue_scripts inside a shortcode function. It is not working.

2
  • Register your scripts with wp_register_script('script-name','./src.js' ) somewhere at the beginning of your plugin/theme or Init hook for example. And enqueue them on the render function wp_enqueue_script( 'script-name' );
    – Hans Koch
    Commented Mar 3, 2016 at 15:38
  • No, this didn't work. I did wp_register_script in the main plugin file that loads first. and added wp_enqueue_script in the shortcode function
    – Prakash
    Commented Mar 3, 2016 at 15:45

1 Answer 1

2
$shortcode = new Shortcode_Class();
class Shortcode_Class
{
    /**
     * If you should add the script or not
     *
     * @var bool
     */
    private $addScript = false;

    public function __construct()
    {
        add_shortcode('test_shortcode', array($this, 'shortcode_content'));

        // wp_enqueue_scripts
        // If you use the below the CSS and JS file will be added on everypage
        // add_action( 'wp_enqueue_scripts', array($this, 'add_shortcode_scripts'));

        // Add styles and scripts to the page
        add_action('wp_footer', array($this, 'add_shortcode_scripts'));
    }

    public function shortcode_content( $attr, $content )
    {
        $this->addScript = true;
        ?>
        <h1>Shortcode Content Being Displayed</h1>
        <?php
    }

    public function add_shortcode_scripts()
    {
        if(!$this->addScript)
        {
            return false;
        }

        wp_enqueue_script('shortcode-js', get_stylesheet_directory_uri() . '/js/shortcode.js', false);
    }
}

This helped!

1
  • what helped? what did you change?
    – Milo
    Commented Mar 3, 2016 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.