简体   繁体   中英

Add specific javascript code to a wordpress page

I have found some code I want to use to a single page in my wordpress site, but I cannot find the way to do it. I am not a developer, but a newbie.

I have html and css ready, but I don't know how to run this javascript code to a page with id 2922 , every time the page loads.

$(function () {
var parent = $("#shuffle");
var divs = parent.children();
while (divs.length) {
    parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});

Thanks for your help, Thodoris

You can do this from jQuery. In your script add condition to check if body has class of that page id is same as your page-id-2922 , if yes then run the code.

I have updated your script, try using it:

$(function () {

    if( $('body').hasClass('page-id-2922') == true ){
        var parent = $("#shuffle");
        var divs = parent.children();
        while (divs.length) {
            parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
        }
    }

});

You can add it into the single.php with a conditional like so:

<?php if ( is_page(3318) ) : ?>
    <script type='text/javascript'>
        $(function () {
            var parent = $("#shuffle");
            var divs = parent.children();
            while (divs.length) {
                parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
            }
        });
    </script>
<?php endif; ?>

It will add the escript on the page only if it is the single post with ID 3318.

EDIT: added right answer and changed to the correct ID.

You can write this code in footer.php[site/wp-content/your-theme/footer.php]

<?php if(get_the_ID()== 2922){ ?>
 <script type='text/javascript'>
        jQuery(function () {
            var parent = jQuery("#shuffle");
            var divs = parent.children();
            while (divs.length) {
                parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
            }
        });
    </script>

or read this https://www.tipsandtricks-hq.com/how-to-add-javascript-in-a-wordpress-post-or-page-1845

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM