Jd Bohn
Jd Bohn

Reputation: 35

adding css to wordpress when shortcode is used

I can't seem to get this function to work and was wondering if someone could take a look for me.

I have some static pages that use a special form, I don't want/need the css loaded on every page of the site though.


function skyform_check_function() {
    global $post
    if (has_shortcode( $post->post_content, 'skyform_function')) {
        wp_enqueue_script( 'add_skyform_css_function');
    }
}
add_action ('wp_enqueue_scripts', 'skyform_check_function');

[skyform_function] is the shortcode for the form function add_skyform_css_function() adds the css. <- this work fine if I just do add_action ('wp_head', 'add_skyform_css_function');

function add_skyform_css_function () {
?>
    <link rel="stylesheet" href="/assets/sky-forms/css/sky-forms.css">
    <!--[if lt IE 9]><link rel="stylesheet" href="assets/sky-forms/css/sky-forms-ie8.css"><![endif]-->

    <script src="/assets/sky-forms/js/jquery.min.js"></script>
    <script src="/assets/sky-forms/js/jquery-ui.min.js"></script>
    <script src="/assets/sky-forms/js/jquery.form.min.js"></script>
    <script src="/assets/sky-forms/js/jquery.validate.min.js"></script>
    <script src="/assets/sky-forms/js/jquery.maskedinput.min.js"></script>
    <script src="/assets/sky-forms/js/jquery.modal.js"></script>

    <!--[if lt IE 10]><script src="/assets/sky-forms/js/jquery.placeholder.min.js"></script><![endif]-->        

    <!--[if lt IE 9]>
        <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <script src="/assets/sky-forms/js/sky-forms-ie8.js"></script>
    <![endif]-->
<?php
}

Upvotes: 2

Views: 1438

Answers (1)

Brian Dillingham
Brian Dillingham

Reputation: 9356

First register your shortcode with add_shortcode or you will not be able to use has_shortcode

The short code needs to be registered with add_shortcode() to be recognized.

function skyform_check_function() {
    global $post;

    if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'skyform_function') ) {
        add_action ('wp_head', 'add_skyform_css_function');
    }
}

add_action('wp_enqueue_scripts', 'skyform_check_function');

add_shortcode('skyform_function', 'skyform');

function skyform() {
    // your shortcode
}

and add you're code to wp_head, because wp_enqueue_script is script by script, not echoing a block.

Upvotes: 2

Related Questions