将wp_get_attachemnt_image与jQuery结合使用,在输出图像之前添加类?

时间:2016-02-29 21:36:52

标签: php jquery

我正在使用wp_get_attachemnt_image获取图像,然后我使用jQuery检查是否是纵向或横向添加相应的类...这种工作但不太好,有时它不适用于某些图像。

有没有办法在调用图像之后但在输出图像之前添加类?

我正在使用此代码来获取图片:

<?php $args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'orderby'=> 'menu_order',
'order'=>'ASC', 
'post_parent' => $post->ID,
);
$images = get_posts( $args );
foreach($images as $image):
echo wp_get_attachment_image($image->ID, 'large');
endforeach;
?>

和此代码添加类:

<script>
jQuery(document).ready(function($){
$('#journal img').each(function(){
$(this).addClass(this.width > this.height ? 'landscape' :  'portrait');
});
});
</script>

我还尝试在echo wp_get_attachment_image($ image-&gt; ID,'large')之前回显脚本;但这似乎没有什么区别。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您最初可能会生成HTML代码,其中每个参与的图片都包含style的类(或直接display: none;)。

然后更改您的JS部件,以便在设置了所需的类时显示图像:

$(this).addClass(this.width > this.height ? 'landscape' :  'portrait').show();