摘录链接到帖子的缩略图

时间:2014-03-27 10:34:12

标签: php wordpress image function post

我对wordpress和PHP很新,刚刚从博客切换过来。我希望有人可以帮助我,因为我一直在寻找网络而没有找到我正在寻找的解决方案,

我想知道是否有办法让摘录显示帖子中的第一张图片,然后将图片链接到实际帖子?我尝试过使用精选图片的变体,但要么我在摘录中获得两张图片,要么在帖子中没有图片......

如果有人知道完成这一切的代码,我会很高兴:)

这是我的索引文件:

    <?php
/**
 * Displays the index section of the theme.
 *
 * @package Theme Horse
 * @subpackage Clean_Retina
 * @since Clean Retina 1.0
 */
?>

<?php get_header(); ?>

<?php
    /** 
     * cleanretina_before_main_container hook
     */
    do_action( 'cleanretina_before_main_container' );
?>

<div id="container">
    <?php
        /** 
         * cleanretina_main_container hook
         *
         * HOOKED_FUNCTION_NAME PRIORITY
         *
         * cleanretina_content 10
         */
        do_action( 'cleanretina_main_container' );
    ?>

</div><!-- #container -->




<?php
    /** 
     * cleanretina_after_main_container hook
     */
    do_action( 'cleanretina_after_main_container' );
?>



<?php get_footer(); ?>

   <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
       <p><?php echo get_new_excerpt(); ?></p>
<?php endwhile;endif;wp_reset_query(); ?>

1 个答案:

答案 0 :(得分:0)

据我了解,您希望帖子中的第一张图片进入您的摘录。所以我有一个更好的解决方案,为什么不在包含你的图像与原始摘录连接的functions.php文件中创建另一个函数?

添加到您的functions.php

function get_new_excerpt(){
    $str = '';
    $img = '<img src="'.catch_that_image().'">';
    $linkedImage = '<a href="'.get_permalink().'" title="'.get_the_title().'">'.$img.'</a>';
    $str .= '<div class="post-image">'.$linkedImage.'</div>';
    $str .= '<div class="post-excerpt">'.get_the_excerpt().'</div>';
    return $str;
}
// Catch first Image from http://css-tricks.com/
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)) {
    $first_img = "/path/to/default.png";
  }
  return $first_img;
}

然后在你的index.php或你要显示此功能的页面中,插入:

<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
       <div class="post">
            <h1 class="post-header"><?php the_title(); ?></h1>
            <div class="post-info">
                <?php echo get_new_excerpt(); ?>
            </div>
       </div>
<?php endwhile;endif;wp_reset_query(); ?>

你可能想添加一些css样式,如:

    <style>
    .post {
        clear: both;
        background-color: #fff;
        border: 1px solid #ccc;
        overflow: hidden;
    }
    .post h1.post-header {
        border-bottom: 1px solid #ccc;
    }
    .post .post-info {
        clear: both;
        overflow: hidden;
    }
    .post .post-image {
        float: left;
        width: 100px;
        height: 100px;
        background-color: #EFEFEF;
    }
    .post .post-image img {
        width: 100%;
        height: 100%;
    }
    .post .post-excerpt {
        float: right;
        width: calc(100% - 120px);
        text-align: left;
    }
</style>

我希望我理解你。我希望它有所帮助。

相关问题