WordPress.org

Ready to get started?Download WordPress

Forums

add js only if condition is true (3 posts)

  1. ced1870
    Member
    Posted 2 months ago #

    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.

  2. bcworkz
    Member
    Posted 2 months ago #

    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.

  3. ced1870
    Member
    Posted 2 months ago #

    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 :)

Reply

You must log in to post.

About this Topic

Tags

No tags yet.