if语句中的query_posts问题

时间:2015-12-03 21:48:08

标签: php wordpress if-statement wp-query

在wordpress博客上遇到麻烦。我试图根据用户来自的网站部分显示具有特定类别的帖子。除了if / else语句中的'query_posts'之外,一切正常。我有以下php:

<?php
/*
Template Name: Blog
*/
get_header(); ?>


<?php
// Find out if the user came to the blog from 'Experienced' or 'College' section of the site
$came_from = wp_get_referer(); 
// Show posts with categories based on where the user came from
if (strpos($came_from,'experienced') !== false) {
    $text = 'test';
    query_posts('cat=experienced-professionals');
    // wp_reset_query();
} else {
    $text = 'heyo';
    query_posts('cat=college-students');
    // wp_reset_query();
}
?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<div style="background:red;width:100%;height:200px;"></div>

<div id="container">
    <div id="content" role="main">

        <h1 class="entry-title"><?php the_title(); ?></h1>
        <p><?php echo $text; ?></p>
        <?php print_r($came_from); ?>
    </div><!-- #content -->
</div><!-- #container -->

<?php endwhile; ?>
<?php endif; ?><!--end the entire loop-->

<?php wp_reset_query(); ?>

<?php get_footer(); ?>

我知道我的referer变量和if / else语句是否正常工作,因为$ text变量应该根据我从博客中获取的网站部分进行更改。但无论我如何访问博客,该页面都会显示所有帖子,并忽略if / else语句中的query_posts类别。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

没关系想出来......希望它可以帮助别人!修正了它:

<?php
/*
Template Name: Blog
*/
get_header(); ?>


<?php
// Find out if the user came to the blog from 'Experienced' or 'College' section of the site
$came_from = wp_get_referer(); 
// Show posts with categories based on where the user came from
if (strpos($came_from,'experienced') !== false) {
    $text = 'test';
    $queryCategory = 'experienced-professionals';
    // wp_reset_query();
} else {
    $text = 'heyo';
    // query_posts('cat=college-students');
    $queryCategory = 'college-students';
    // wp_reset_query();
}
?>

<?php query_posts( array ( 'category_name' => $queryCategory ) ); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<div style="background:red;width:100%;height:200px;"></div>

        <div id="container">
            <div id="content" role="main">

                <h1 class="entry-title"><?php the_title(); ?></h1>
                <p><?php echo $text; ?></p>
                <p><?php echo $queryCategory; ?></p>
                <?php print_r($came_from); ?>
            </div><!-- #content -->
        </div><!-- #container -->

<?php endwhile; ?>
<?php endif; ?><!--end the entire loop-->

<?php wp_reset_query(); ?>

<?php get_footer(); ?>