Support » Plugins » Hacks » add js only if condition is true

  • Hi
    I’m developping my plugin and it works :), that is the good news
    Now I would like to make it correctly.
    1/ I have a fonction that check if a word exist in the content:

    add_filter(‘the_content’, array( $this, ‘searchkey’));

    2/ I have an action to load my CSS and JS files

    add_action(‘wp_enqueue_scripts’, array( $this, ‘load_assets_files’));

    The problem here is that even if my word is not found in the content, the CSS and JS files will be loaded. I want to
    if (word is found) {
    load my js and css

    but if I use <script type=”text/javascript”> in my condition, it will be added for each post content. It needs to be added into the head.
    If I use a “add_action(‘wp_head’)” into my condition which is in the_content filter, then it does not work.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz


    The only way to check post content before the head portion is output would be to get the query results from ‘the_posts’ filter. Go through and search all of the content for each post, essentially running your own loop. If the word is found, it shouldn’t be too late to add a callback to ‘wp_enqueue_scripts’ that loads your JS and CSS pages.

    thank you for your reply
    then if I do this it will not be applied to the pages, only the posts.
    as I look for a css class into my js file it will not overload the page if nothing is found, but I would have done this better
    for now I will let this as I have done 🙂

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘add js only if condition is true’ is closed to new replies.