Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 188 Vote(s) - 3.6 Average
  • 1
  • 2
  • 3
  • 4
  • 5
WordPress: How to filter posts by category using $wp_query?

#1
I built a custom theme on WordPress with a static front page and no page set in **Settings > Reading Settings > Front page displays** as a posts page. I'd like to display posts, however, based on their categories throughout the site on different static pages. Therefore, I will never declare a posts index page through the console. And so I use the $wp_query function.

How can I add a filter to this script that only displays posts in the category "apples" (for example)? Right now, this script shows all posts regardless of category.

<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=1' . '&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post();
?>

<h2><a href="<?php the_permalink(); ?>" title="Read"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php the_date(); ?>

<?php endwhile; ?>

<?php if ($paged > 1) { ?>
<p><?php previous_posts_link('Previous page'); ?>
<?php next_posts_link('Next page'); ?></p>
<?php } else { ?>
<p><?php next_posts_link('Next page'); ?></p>
<?php } ?>

<?php wp_reset_postdata(); ?>
Reply

#2
Delete your first php block and replace it with this

<?php
$args = array (
'showposts' => '1',
'category_name' => 'apples',
'paged' => $paged
);
$the_query = new WP_Query( $args );

if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
?>

For more information

[To see links please register here]

Reply

#3
> You have to use `category_name` (string - use category slug) or `cat`
> (int - use category id), to get post by category in `WP_Query::query()`.

Here is an example:

$category_name = 'apples'; //replace it with your category slug
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=1' . '&paged=' . $paged . '&category_name=' . $category_name);
//...
//...

Hope this helps!
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through