-1

I have been a designer by trade for years however I am working with WordPress for a client and have been managing to get by with working with hooks... I am, however now at a standstill.

On the homepage I have two areas which will be pulling information from the database:

<?php 
    $thumb_posts = get_posts(array('category' => '6', 'orderby' => 'rand', 'numberposts' => 2, 'meta_key' => '_thumbnail_id' ));
if($thumb_posts) { ?>
<?php foreach( $thumb_posts as $post ) {
echo '<div class="feature"><div class="thumbnail">
<a href="' . get_permalink($header_thumb->ID) . '">' . get_the_post_thumbnail($header_thumb->ID,array(240,170)) . '</a></div>';
$url = get_permalink($post->ID);
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
$json = json_decode($filecontent);
$count = $json->$url->comments;
if ($count == 0 || !isset($count)) {
$count = '0';
} elseif ( $count == 1 ) {
$count = '1';
} else {
$count .= '';
}
echo '<h3 class="title"> <a href="' . get_permalink($header_thumb->ID) . '#comments"     class="comments">' . $count . '</a> <a href="' . get_permalink($header_thumb->ID) . '"> ' . get_the_title($ID) . ' </a> </h3></div>';
} ?>

Which I did not write, but calls the facebook comment count of the random post with title and thumbnail.

Here is my problem... Once I place my second code AFTER this it throws off the count/image retrieval. However, if I place this code BEFORE everything works great.

<?php 
$thumb_posts = get_posts(array('category' => '6', 'orderby' => 'rand', 'numberposts' => 2, 'meta_key' => '_thumbnail_id' ));
if($thumb_posts) { 
?>

<?php 
global $post;
$myposts = get_posts('numberposts=20');
foreach($myposts as $post) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> | 
<span class="post-info"> <?php echo human_time_diff( get_the_time('U'),
current_time('timestamp') ) . ' ago'; ?> </span></li>
<?php endforeach; ?>

In my thought process, I need to somehow make it so the second code doesn't somehow throw off the first independent code.

4

1 回答 1

1

由于这组行,它不是“从相同的参数中提取”:

global $post;
$myposts = get_posts('numberposts=20');
foreach($myposts as $post) :

为了:

  1. 通过这样做,您将对Wordpress 设置global $post的全局变量的引用提升到您的范围内。代表当前帖子。$post$post
  2. 然后,您从 WP 获得许多帖子并将其设置为$myposts. 这可以。
  3. 但是,不好的是,您随后会使用 as unique$myposts element进行循环$post。最后一个分配导致 Wordpress 的全局$post被重置并破坏所有其余部分。

考虑这样做:

<?php 
global $post;
$myposts = get_posts('numberposts=20');
foreach($myposts as $current_post) : 
?>

这根本不会修改全局范围,这是 Wordpress 保存一些东西的地方。

于 2013-05-02T23:00:21.663 回答