php wordpress query

2019-08-05 01:39发布

问题:

I had posted this earlier on Stack Overflow, but couldn't get a positive result. I thought I should do this again.

<?php require_once 'news/wp-config.php';
$howMany = 0;
$query ="SELECT `ID`, `post_title`,'post_category', `guid`,SUBSTRING_INDEX(`post_content`, ' ', 100) AS `post_excerpt` FROM $wpdb->posts WHERE `post_status`= \"publish\" AND `post_type` = \"post\" AND post_category != \"1\" ";
$posts = $wpdb->get_results($query);
$posts = array_reverse($posts);
foreach($posts as $post)
{
    if($howmany<10)
    {
        $link = $post->guid;
        echo "<li><a target='_blank' href='$link'>$post->post_title</a></li>";
        $howmany++;
    }   

}                   
?>

I want the above code not to display posts from Category 1. I think I have done everything right, but still I can't get the result that I want.

One more thing is if I even explicitly ask the query to display the posts from category 3 or 4, it doesn't happen. It ends up displaying posts from all categories.

回答1:

You should use the query_posts() function. If not, at least get rid of that $howMany variable and instead append "LIMIT 10" to your sql query.

Here is an example of getting a category prepped for the loop:

<?php
     // Borrowed heavily from link above...
     $categoryvariable=1; // assign the variable as current category
     $numposts = 10;
     // Set up the query
     $query= 'cat=' . $categoryvariable. '&orderby=date&order=ASC&showposts='.$numposts;      
     query_posts($query); // run the query

//The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
     // Do all your echo stuff here
endwhile; else:

endif;

//Reset Query
wp_reset_query();

?>


回答2:

I would second using the wordpress functions.

Here's a great resource http://codex.wordpress.org/Function_Reference/query_posts

The correct syntax would be query_posts('category__not_in=1');

I think you said you didn't want it in category 1.