Reputation: 1183
I was wondering to do separate blog pages for separate category posts. What I was able to find was running query by category number, but this is not dynamic enough for me as I would like to run query on page title which is = category name.
Basically on page "events" I would like to display blog posts that are under category named "events"(category name == page title), and so on.
Any insights on how to achieve this would be great. What I tried to do and failed, was:
<?php query_posts('category_name='.get_the_title()); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div>
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php endwhile; else: ?>no match<?php endif; ?>
Thanks in forward for any insights, links or notices.
Upvotes: 1
Views: 13541
Reputation: 9951
First of all, never ever use query_posts
. It breaks the main query, reruns queries that slows your page, incorrectly sets vital functions used by plugins, functions like get_queried_object()
and it messes up pagination.
If you need to run custom queries, make use of WP_Query
.
To come to your original issue, the default category parameters don't make use of category names, only slugs and ID's. The slugs are controllable, so you might want to use slugs with the category_name
parameter.
If you do need to pass category names, then you should use a tax_query
which do accept names passed to the terms
parameter
You can pass the following with your parameters
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'name',
'terms' => 'name of your category',
'include_children' => false,
) ,
);
Upvotes: 3
Reputation: 3425
You can do it with get_post
function.
Do like this:
<?php
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div>
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php endforeach;
wp_reset_postdata();
?>
Let me know if you need further help.
Upvotes: 2