Using wordpress I am grabbing the first image attachment from the posts. This works fine:
<?php
global $post;
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'menu_order',
'order' => 'ASC',
'numberposts' => 2 );
$images = get_posts($args);
if ( $images ) {
$i = 0;
while($i <= 1){
$image = wp_get_attachment_url( $images[$i]->ID );
echo "<img src='$image' />";
$i++;
}
}
?>
I am also trying to process these images which in conjunction with timthumb resizes the images depending on browser size. I can only get this to work on one of the two images. I would expect it to log and resize twice but the script is not running in the loop. Can someone please help ? This is what the full snip I am working with looks like :
<?php
global $post;
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'menu_order',
'order' => 'ASC',
'numberposts' => 2 );
$images = get_posts($args);
if ( $images ) {
$i = 0;
$z = 1;
while($i <= 1){
$image = wp_get_attachment_url( $images[$i]->ID );
echo "<img src='$image' class='image_$z' />";
?>
<script type="text/javascript">
var image = "<?php echo $image ; ?>";
var under700_<? echo $z ?> = "/wp-content/themes/Loupe/scripts/timthumb.php?src=<? echo $image ?>&w=340";
var under900_<? echo $z ?> = "/wp-content/themes/Loupe/scripts/timthumb.php?src=<? echo $image ?>&w=440";
function imageresize() {
var contentwidth = $('#two_up').width();
if ((contentwidth) < '700'){
console.log('under 700_<? echo $z ?>' + under700_<? echo $z ?>);
$('img .image_<? echo $z ?>').attr('src', under700_<? echo $z ?>);
} else if ((contentwidth) < '900') {
// console.log('under 900');
$('img .image_<? echo $z ?>').attr('src', under900_<? echo $z ?>);
}
else {
image;
}
}
</script>
<?php
$i++;
$z++;
}
}
?>
Use
json_encode()
it makes a JavaScript object (or array or combined) of a PHP variable and makes itI’m assuming
$images
is an array; if not, tweak this solution to fit.Javascript:
I would recommend setting specific height/width in your css and then using jquery to replace the images as the page loads.
As an alternative, try doing the entire processing in php. You’ll save your users loading time, and imho, it’s much easier.
http://www.imagemagick.org/script/index.php
What I guess you are trying to do is something like this:
But, as suggested before by @Toast: I’d do this in PHP and prevent the user from reloading all the images on the page. Because that is effectively done by the above code.
If you have the path of the source image files that you are trying to resize, then you could use getimagesize to get the image size, and adjust the src uri off the images accordingly.
The only guess I have, at you using javascript to do this, is that you are using the DHTML/CSS box model to help you calculate the width of the container (
#two_up
) for the images. This I would strongly discourage, but still the above code should work! 😉