0

我需要在添加到 Wordpress 侧边栏的滑块中显示属于类别的帖子的主图像,如果我在页面中,代码可以正常工作,但不在主页或搜索结果页面中,这是我的代码:

<ul id="sliderContent">
    <?php
 $joiners .= " LEFT OUTER JOIN wp_term_relationships r ON r.object_id = wp_posts.ID
 LEFT OUTER JOIN wp_term_taxonomy x ON x.term_taxonomy_id = r.term_taxonomy_id 
 LEFT OUTER JOIN wp_terms t ON t.term_id = x.term_id ";
 $sentgeters .= " AND t.slug = 'CATEGORY_NAME_GOES_HERE' ";

        $querystr = "
                SELECT wp_posts.* 
                FROM wp_posts ".$joiners."  
                WHERE wp_posts.post_status = 'publish' 
                AND wp_posts.post_type = 'post' ".$sentgeters."
                ORDER BY RAND() " ;

        $pageposts = $wpdb->get_results($querystr, OBJECT);

    ?>

    <?php if ($pageposts): ?>
     <?php global $post; ?>
     <?php foreach ($pageposts as $post): ?>
     <?php setup_postdata($post); ?>

    <li class="sliderImage">
        <a href="<?php the_permalink() ?>"><?php main_image(); ?></a>
        <span class="top"><?php the_title(); ?></span>
    </li>


    <?php endforeach; ?>
    <?php endif; ?>
    <div class="clear sliderImage"></div>
</ul>

main_image() 是我编写的一个函数,用于显示上传的第一张图片。任何的想法?

4

1 回答 1

3

为什么要编写自定义查询?在 wordpress 中,建议使用 get_posts 或 query_posts。

请参阅:http ://codex.wordpress.org/Template_Tags/get_posts

<?php $posts_array = get_posts( array(
    'posts_per_page'   => 5,
    'offset'           => 0,
    'category'         => $cat_id,
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'include'          => '',
    'exclude'          => '',
    'meta_key'         => '',
    'meta_value'       => '',
    'post_type'        => 'post',
    'post_mime_type'   => '',
    'post_parent'      => '',
    'post_status'      => 'publish',
    'suppress_filters' => true ) ); ?>

注意: category参数需要是类别的ID,而不是类别名称。

要获取类别 ID:

<?php $cat_id = get_category_by_slug( $slug ); ?>

和foreach:

foreach ($posts_array as $p) {
  print_r ($p);
}

您的代码变得可读、易于维护,最重要的是您不会遇到问题。

于 2013-09-28T10:22:28.867 回答