How to customize the_content() on Wordpress for the homepage?

那年仲夏 提交于 2019-12-12 05:28:08

问题


I'm trying to customize a wordpress home page, exactly, the_content() function. the website I'm trying to use is http://sportsponsorizzazioni.com/

If in the file about "loop" I use the function "the_content()" it gives me a list of full articles on the home page, with the image I've included in the post body and the text formatted as I want. Using the function "the_excerpt()" in an other way, show me only the excerpt text, like 5 rows, without any image.

I just want to display on my home page, the first part of an article, with "read more" button after, and the image, but then I do a substring operation on the_content(''), it only gives me first X characters but without image... even if in my post the tag is on the start of the post.

I need something automatic, can't add a "thumbnail image" or a "featured image" on every single post, is there a way to modify "the_content('')" to let me take for example only the first 30 words of my post with the image? Or (better) is there a way to include in "the_excerpt()" the image coded in my article?

Thanks a lot!


回答1:


This plugin does exactly what you're trying to do. See item number 4 in the FAQ section for pulling images from post content.




回答2:


In case you don't want to go to the plugin solution, 1. add custom field to posts, for example with name of post-image and value of image url(try to use the custom field for all posts). 2. include a code similar to below in your home.php

<?php if(have_post()):

  while(have_post()):
   the_post(); ?>

   <div id="<?php the_ID();?>" <?php post_class();?>>
      <!--output the excerpt-->
            <?php the_excerpt(); ?>
        <!--access the image source as below-->
         <?php $img_src=get_post_meta($post->ID,'post-image',$single=true); ?>

          <!--check if $img_src is not empty, in case there will be 
          a post without post-image custom field.
          -->
          <?php if($img_src !==''): ?>
          <img src="<?php $img_src;?>" alt="<?php the_title();?>"      class="home_image" />
                        <?php endif;?>
                          <!--whenever there is a post with no image, you may like 
                             to add else logic here and do something-->
     </div>

   <?php endwhile; else: ?>

   <!--some error message-->

   <?php endif; ?>


来源:https://stackoverflow.com/questions/13595544/how-to-customize-the-content-on-wordpress-for-the-homepage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!