0

Here's the markup in my index.php:

<div class="post-thumb"> 

</div>

I want jQuery to put this below code in the div above with the class of "post-thumb" when window's width is less than 1024 pixels:

<?php if ( has_post_thumbnail()) the_post_thumbnail('small-thumb'); ?>

and this one when width is larger than 1024 pixels:

<?php if ( has_post_thumbnail()) the_post_thumbnail('large-thumb'); ?>

I've already put these two codes above in separate files called "large-thumb.html" and "small-thumb.html" in the Wordpress root directory.

I'm using this piece of code in jQuery but it doesn't work:

$(document).ready(function(){
    if ( $(window).width() > 1025) {
        $('.post-thumb').load("large-thumb.html");
    }
    else {
        $('.post-thumb').load("small-thumb.html");
    }
});

The jQuery above is in a folder named "js" in the Wordpress root directory.

What am I doing wrong? What should I do for this to work?

I can't use CSS and media queries because it'll increase the size of the index page by loading both post_thumbnails sizes.

Thanks.

  • Well PHP is not going to execute in a .html file for a start, is it? – vancoder Oct 28 '15 at 16:33
  • You're absolutely right! I thought I could use html file just as a container for the code. – Kevin Armstrong Oct 28 '15 at 16:39
1

You cannot just create .html files arbitrarily, WP won't recognize them and any PHP code won't work in html file in first place (typically).

While you could bend this into working with some effort it would be bad approach since making Ajax request to WP will cause another core load and essentially double the load on the server (per each image).

The normal WP practice to pass data to JS script is to use wp_localize_script() for it. You can generate sizes in advance and that data will load together with page itself so script can immediately make use of it, without any extra requests.

  • I solved my problem by CSS through cropping the post_thumbnail in small widths. Thanks anyway! Appreciate your time. – Kevin Armstrong Oct 28 '15 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.