使用wordpress将图像移动到另一个div

时间:2013-03-15 12:50:56

标签: wordpress image

我是Wordpress的新手,这是我的第一个Wordpress网站,所以请耐心等待。

这是我的index.php:

<?php get_header(); ?>
   <div id="content">
        <section id="posts">
                <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
                <section class="post">
                    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?>        </a></h2>
                    <div class="holder">

                    </div>
                    <p><?php the_content(); ?></p>
                </section>
                <?php endwhile; else: ?>
     <p><?php _e('Nothing here, sorry.'); ?></p>
     <?php endif; ?>
        </section>
        <aside>
            <?php get_sidebar(); ?>
        </aside>
         <div style="clear:both"></div>
        </div>   
        <div class="push"></div>
    </div>
</div>  
    <?php get_footer(); ?>

基本上,我想要的是从帖子中找到第一张图片,并将其放在.holder div中。它应该类似于jQuery中的detach()和append()。

我知道我应该使用过滤器和操作,但我不知道如何开始,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

在你的文件functions.php中:

<?php function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];

if(empty($first_img)){ 
 //Defines a default image
 $first_img = "/images/default.jpg";
}
return $first_img;
}
?>

并在你的文件index.php中输入:

<div class="holder">
   <img src="<?php echo catch_that_image() ?>" />
</div>