I have found a few articles about using PHP in JS but nothing has helped me so far, so here is my question. I need to call wordpress post content (title, excerpt and thumbnail) into a JS “preview” functionality (essentially calling posts with the ThumbnailGridExpandingPreview). I have been able to make the “expanding preview” open from the post thumbnail and title, however I am having trouble adding the post content to the preview.
I am attempting to add the php calls to the preview function in the “grid.js” file, however I am not sure exactly how to “minify” the php code. See below for my code.
The code as it reads originally:
this.$title = $( '<h3></h3>' );
And here is how I am attempting to call the post title:
this.$title = $( '<h3><?php echo get_the_title(); ?></h3>' );
Any help would be hugely appreciated! Thanks in advance.
Some clarifications: PHP is a server side language; this means that it can be parsed and executed only server-side.
That said, you have two options here, one more elegant, the other a bit crappy (i would use it only in really rare and limited cases):
Elegant solution: WordPress Ajax. Setup an ajax-callable function in your functions.php file which returns data-populated html:
a. Add an ajax-callable action to your functions.php file:
b. Specify the function to be called (specify a second one for non logged-in users in case you need it)
c. Cook the frontend-code, somewhere in the template (obviously make it so that’s available to your grid.js calls). You’ll need to have $post populated with your post data. I tend to use a global wrapper:
d. From now on, it’s up to you to make the ajax call (I don’t have any references to your code) but it’s pretty straightforward:
See http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action) for this.
This is a good tutorial (found it on the first page of Google): http://wp.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/
Crappy solution: generated data-populated JS code (i would stick to a JS object). In this case, you will need an additional script tag inside your page (template or whatever else has access to PHP) in which you’ll output JS valid code: