I want my jQuery script run every time post page is open or loaded. I have tried use echo
in script but not work
Where should I put it to make the script run?
single.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<?php
/**
* The template for displaying all single posts and attachments
*
* @package WordPress
* @subpackage Twenty_Fifteen
* @since Twenty Fifteen 1.0
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
// Start the loop.
while ( have_posts() ) : the_post();
echo "
<script type=\"text/javascript\">
alert("hello!"); //placeholder script
</script>
";
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
// Previous/next post navigation.
the_post_navigation( array(
'next_text' => '<span class="meta-nav" aria-hidden="true">' . __( 'Next', 'twentyfifteen' ) . '</span> ' .
'<span class="screen-reader-text">' . __( 'Next post:', 'twentyfifteen' ) . '</span> ' .
'<span class="post-title">%title</span>',
'prev_text' => '<span class="meta-nav" aria-hidden="true">' . __( 'Previous', 'twentyfifteen' ) . '</span> ' .
'<span class="screen-reader-text">' . __( 'Previous post:', 'twentyfifteen' ) . '</span> ' .
'<span class="post-title">%title</span>',
) );
// End the loop.
endwhile;
?>
</main><!-- .site-main -->
</div><!-- .content-area -->
<?php get_footer(); ?>
You're not escaping the "Hello" text :
alert("hello!");
Try this instead :
alert('hello!'); // or alert(\"hello!\");
The best way is probably to use fopen
eg
<?php
$filename = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
$myfile = fopen($filename, "rb");
if (FALSE === $myfile) {
exit("Failed to open stream to URL");
}
while (!feof($handle)) {
$contents = stream_get_contents($myfile, 8192));
}
fclose($myfile); //close the file again when necessary
?>
You could alternatively reverse the backslashes and echo the script in the traditional way
<?php echo "<script type=\"text/javascript\" src=\"jquery.min.js\"></script>; ?>
Note i haven't completed the jquery path (that's the downside.. it's a long path! .. lots of backslashes..)
I think use your script out of loop in single.php file or try another way.
if( jQuery(".single").hasClass(".single-post") ){
alert("hello!"); // whatever you want to process.
}
Use this code in your main js file. i think it will help you
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.