抓图片 - Wordpress PHP

时间:2014-01-22 02:47:06

标签: php wordpress

我在这里有一个功能,它将抓住最近的两个帖子并抓住这两个帖子中发布的图像。问题是,它一直抓住第一个帖子的第一张图片而不是第二张图片:

代码:

function getImageFeatured($num) {
  global $more;
  $more = 1;
  $link = get_permalink();
  $content = get_the_content();
  $count = substr_count($content, '<img');
  $start = 0;
  for($i=1;$i<=$count;$i++) {
  $imgBeg = strpos($content, '<img', $start);
  $post = substr($content, $imgBeg);
  $imgEnd = strpos($post, '>');
  $postOutput = substr($post, 0, $imgEnd+1);
  $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
  $image[$i] = $postOutput;
  $start=$imgEnd+1;
}
 if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
  $more = 0;
}

$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
    echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . getImageFeatured('1')  .'</a></li> ';

}

不确定为什么它只发送第一篇文章的第一张图片。

赞赏建议和想法。

编辑:

修订版:

.....above function I posted....   
 global $post;
 $args = array( 'numberposts' => '2' );
 $recent_posts = wp_get_recent_posts( $args );
 foreach( $recent_posts as $post ){
    setup_postdata( $post );
    echo '<li><a href="' . get_permalink() . '" title="Look '.get_the_title_attribute().'" >' . getImageFeatured('1')  .'</a></li> ';

 }

 wp_reset_postdata();

这对我来说都不起作用。看来如果我使用setup_postdat...它不会处理但是如果我删除它会通过但不会按照我的要求进行,但是我说的是问题。

1 个答案:

答案 0 :(得分:0)

get_the_content正在获取循环中帖子的内容。您可以在两个帖子上运行该功能,但它仍然可以获取循环中帖子的内容。

您编写的函数需要一些严重的改进,但为了让它以最快的方式工作,可以用以下方法替换现有的foreach循环:

global $post;

foreach( $recent_posts as $post ){
    setup_postdata( $post );
    echo '<li><a href="' . get_permalink() . '" title="Look '.get_the_title_attribute().'" >' . getImageFeatured('1')  .'</a></li> ';

}

wp_reset_postdata();