最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

shortcode - How to force that styles are enqueued in the header?

programmeradmin2浏览0评论

I have a plugin processing a shortcode, that needs specific styles. For this I used wp_enqueue_style.

As I just need to enqueue the CSS upon certain parameters of the shortcode, I call wp_enqueue_style inside a method launched from my shortcode entrypoint, and not from a hook added in the plugin's constructor (I use a PHP class).

As a result, the CSS is indeed inserted, but before the </body> tag and not in the <head>, whereas if wp_enqueue_style is called from the constructor, the CSS is enqueued in the head.

This prevents the plugin's user from adding its own CSS for overriding mine (if it's added in the body).

Is it possible to call wp_enqueue_style after the plugin's class is built and having the style enqueued in the header?

Or is there another way to achieve this? My goal is to avoid enqueuing unnecessary styles (and scripts).

NB : For information I have exactly the same behavior with wp_enqueue_script for scripts: whether it's in the head or in the body depends on when it's called…

Thanks

Edit:

Here's a tiny plugin showing my shortcode plugin pattern and what I want to achieve;

class MyPlugin
{
    protected $myoption;

    public function __construct()
    {
            add_action('init', array($this, 'add_hooks'));
    }

        public function add_hooks()
        {
            add_action('wp_enqueue_scripts', array($this,'hook_javascript'));
            add_shortcode ('myshortcode', array($this, 'process_shortcode'));
        }

        public function hook_javascript()
    {
            global $post;
            if( is_a( $post, 'WP_Post' )
               && has_shortcode( $post->post_content, 'myshortcode') ) 
            {
        // IF ENQUEUED HERE, THE STYLE IS IN THE HEAD, BUT IT'S INSERTED UNCONDITIONNALLY
                wp_enqueue_style ('mycss', plugins_url('/js/mycss.css', __FILE__ ));
            }
        }

        protected function processParams ($atts)
        {
            $attributes = shortcode_atts( array('myoption' => NULL), $atts );
        $this->myoption = $attributes['myoption'];

        if (isset($this->myoption)) {
        // I want to enqueue the style only if 'myoption' attribute is set
        // IF ENQUEUED HERE, THE STYLE IS IN THE BODY !!!
                wp_enqueue_style ('mycss', plugins_url('/js/mycss.css', __FILE__ ));
            }
    }

        public function process_shortcode ($atts, $content = "")
        {
            // Check parameters
                $this->processParams ($atts);
    }
}

发布评论

评论列表(0)

  1. 暂无评论