How can I do that ? Store the_content() into a variable . What I've tried :
<script type="text/javascript">
window.the_content = "<?php the_content(); ?>";
</script>
and this
<?php
ob_start();
the_content();
$content = ob_get_clean();
?>
<script type="text/javascript">
window.the_content = "<?php echo $content; ?>";
</script>
The problem is that what's echo-ed it's a multi-line string and that can't be stored as a javascript variable. I tried to trim() chop() htmlentities_decode() the string but it's useless.
I know that there's a function <?php echo get_the_content(); ?>
that take off the html tags but the spaces and line-breaks are still there. I want to be able to parse the_content() via jquery .
Copy paste of the output from Google Chrome Developer Tool :
window.the_content = "<h1>Welcome to dasqwe tsqwe dwemo site</h1>
<p> </p>
<p>asdioquwidqwd</p>
<p>qwdoqwkdpqkwdkoqpwodkqwodpqwd</p>
<p>qwdkpoqwkdpqwokdpqwokdpqwkdpqwodkq</p>
<p>wdqwodkqpowkdpqwkdpqwkdopqwkdoq</p>
<p>wdqkowpdkqwpokdpoqkwdpqowkdpoqwkdqwd</p>
<p><span id="more-13"></span></p>
<h1>Page 2</h1>
<p>qwiodjiqwjdqiowjdioqwjdiqwd</p>
<p>qwdjoqwijdoqiwjdioqwjiodjqwodjqowdijas</p>
<p>dqoijwdioqjwdoqjwiodjqwodjqwdjasdqwodijqowdjqiowjdoqjdoad</p>
<p>qwodiqwjdoiqwdijoqwdqwiqiodijoqwdjiqwq</p>
<p> </p>
";
Try using json_encode
, it should escape most of the characters that would make it break
<?php
ob_start();
the_content();
$data = ob_get_contents();
ob_end_clean();
?>
window.the_content = <?php echo json_encode($data); ?>;
You could also just strip out the new lines
window.the_content = "<?php str_replace("
","",the_content()); ?>";
Note that you would have to do other stuff to make sure it doesnt break, for instance escape double quotes etc.
Please replace all the linebreaks to <br/>
:
<script type="text/javascript">
window.the_content = "<?php
ob_start();
the_content();
$content = ob_get_clean();
echo str_replace("
","<br/>", str_replace("", "", $content));
?>
</script>
And on the JS-side:
$( '.content' ).the_content);
JSON Encoding on the PHP side and decoding on the Javascript side will handle this for you.
<?php
ob_start();
the_content();
$content = ob_get_clean();
?>
<script type="text/javascript">
window.the_content = <?php echo json_encode($content); ?>;
</script>