display wordpress posts by sub category - php

I am new in wordpress, I am using wordpress Version 4.5, I like to display posts by subcategories, anyone please help how can I do this.
This is what I want
PARENT CATEGORY NAME
SUB CATEGORY 1
Post 1
Post 2
SUB CATEGORY 2
Post 3
Post 4
SUB CATEGORY 3
Post 5
Post 6
...
Thanks in advance

If I am not wrong you need this, you need double loop to fetch the posts under subcategories
this is how you get current page category
<?php
$categories = get_the_category();
$catID = $categories[0]->cat_ID;
?>
and then do this by using above catID
<?php
$subcats = get_categories('child_of=' . $catID);
foreach($subcats as $subcat) {
echo '<h3>' . $subcat->cat_name . '</h3>';
echo '<ul>';
$subcat_posts = get_posts('cat=' . $subcat->cat_ID);
foreach($subcat_posts as $subcat_post) {
$postID = $subcat_post->ID;
echo '<li>';
echo '<a href="' . get_permalink($postID) . '">';
echo get_the_title($postID);
echo '</a>';
echo '</li>';
}
echo '</ul>';
}
?>

If you want to show all the categories that have subcategories with their respective subcategories that have posts with their respective posts, you can easily do that with the following function, as long as you know the slug of the taxonomy and the post type.
For example if you have a custom post type called 'books' and a custom taxonomy to classify your books called 'topic',
then you would call this function using
ow_categories_with_subcategories_and_posts( 'topic', 'book' );
That will display a list of all the topics with their respective subcategories followed by the books that belong to each subcategory.
Something like
Drama
drama subcategory 1
book1
book2
book3
drama subcategory 2
book4
book5
Comedy
comedy subcategory 1
book6
book7
comedy subcategory 2
book8
book9
The following is the code for this:
function ow_categories_with_subcategories_and_posts( $taxonomy, $post_type ) {
// Get the top categories that belong to the provided taxonomy (the ones without parent)
$categories = get_terms(
array(
'taxonomy' => $taxonomy,
'parent' => 0, // <-- No Parent
'orderby' => 'term_id',
'hide_empty' => true // <!-- change to false to also display empty ones
)
);
?>
<div>
<?php
// Iterate through all categories to display each individual category
foreach ( $categories as $category ) {
$cat_name = $category->name;
$cat_id = $category->term_id;
$cat_slug = $category->slug;
// Display the name of each individual category
echo '<h3>Category: ' . $cat_name . ' - ID: ' . $cat_id . ' - Slug: ' . $cat_slug . '</h3>';
// Get all the subcategories that belong to the current category
$subcategories = get_terms(
array(
'taxonomy' => $taxonomy,
'parent' => $cat_id, // <-- The parent is the current category
'orderby' => 'term_id',
'hide_empty' => true
)
);
?>
<div>
<?php
// Iterate through all subcategories to display each individual subcategory
foreach ( $subcategories as $subcategory ) {
$subcat_name = $subcategory->name;
$subcat_id = $subcategory->term_id;
$subcat_slug = $subcategory->slug;
// Display the name of each individual subcategory with ID and Slug
echo '<h4>Subcategory: ' . $subcat_name . ' - ID: ' . $subcat_id . ' - Slug: ' . $subcat_slug . '</h4>';
// Get all posts that belong to this specific subcategory
$posts = new WP_Query(
array(
'post_type' => $post_type,
'posts_per_page' => -1, // <-- Show all posts
'hide_empty' => true,
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'terms' => $subcat_id,
'field' => 'id'
)
)
)
);
// If there are posts available within this subcategory
if ( $posts->have_posts() ):
?>
<div>
<?php
// As long as there are posts to show
while ( $posts->have_posts() ): $posts->the_post();
//Show the title of each post with the Post ID
?>
<p>Post: <?php the_title(); ?> - ID: <?php the_ID(); ?></p>
<?php
endwhile;
?>
</div>
<?php
else:
echo 'No posts found';
endif;
wp_reset_query();
}
?>
</div>
<?php
}
?>
</div>
<?php
}
Then if you ONLY want to get the subcategories related to comedy, and you want to provide the 'comedy' slug as a filter to get something like:
comedy subcategory 1
book6
book7
comedy subcategory 2
book8
book9
Then you would call the following function like this:
ow_subcategories_with_posts_by_category( 'topic', 'book', 'comedy' );
And the function to do that will be:
function ow_subcategories_with_posts_by_category( $taxonomy, $post_type, $term ) {
$category = get_term_by( 'slug', $term, $taxonomy );
$cat_id = $category->term_id;
// Get all subcategories related to the provided $category ($term)
$subcategories = get_terms(
array(
'taxonomy' => $taxonomy,
'parent' => $cat_id,
'orderby' => 'term_id',
'hide_empty' => true
)
);
?>
<div>
<?php
// Iterate through all subcategories to display each individual subcategory
foreach ( $subcategories as $subcategory ) {
$subcat_name = $subcategory->name;
$subcat_id = $subcategory->term_id;
$subcat_slug = $subcategory->slug;
// Display the name of each individual subcategory with ID and Slug
echo '<h4>Subcategory: ' . $subcat_name . ' - ID: ' . $subcat_id . ' - Slug: ' . $subcat_slug . '</h4>';
// Get all posts that belong to this specific subcategory
$posts = new WP_Query(
array(
'post_type' => $post_type,
'posts_per_page' => -1, // <-- Show all posts
'hide_empty' => true,
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'terms' => $subcat_id,
'field' => 'id'
)
)
)
);
// If there are posts available within this subcategory
if ( $posts->have_posts() ):
?>
<div>
<?php
while ( $posts->have_posts() ): $posts->the_post();
//Show the title of each post with the Post ID
?>
<p>Post: <?php the_title(); ?> - ID: <?php the_ID(); ?></p>
<?php
endwhile;
?>
</div>
<?php
else:
echo 'No posts found';
endif;
wp_reset_query();
}
?>
</div>
<?php
}

Related

How to query products by their categories woocommerce

Im building a quick order form/ order table in Woocommerce
What I'm going for is something like this
Main category one
Subcategory
product
product
Subcategory
product
product
Main category two
Subcategory
product
product
Subcategory
product
product
My question is how do I query products under their correct categories
This is what i have so far
<?php
$custom = array(
'post_type' => 'product',
'posts_per_page' => 100,
);
$cust_query = new WP_Query( $custom );
if ( $cust_query->have_posts() ) :
while( $cust_query->have_posts() ) : $cust_query->the_post();
$cat = get_the_terms( get_the_ID(), 'product_cat' );
?>
<?php echo $cat[0]->name; ?>
<div><?php the_title();?></div>
<?php endwhile;
endif;
This is querying each category one at a time I want all product that have the same category to be under the correct category with the category only printed once
Try with below code. Here i have assumed that you are having one level category only.
Main category one //level 0
Subcategory //level 1
product
product
Subcategory
product
product
Main category two //level 0
Subcategory //level 1
product
product
Subcategory
product
product
<ul class="category-sidebar">
<?php
$get_parent_cats = array(
'parent' => '0', //get top level categories only
'taxonomy'=>'product_cat',
'hide_empty' => false
);
$all_categories = get_categories( $get_parent_cats );//get parent categories
foreach( $all_categories as $single_category ){
//for each category, get the ID
$catID = $single_category->cat_ID;
echo '<li>' . $single_category->name . ''; //category name & link
$get_children_cats = array(
'child_of' => $catID, //get children of this parent using the catID variable from earlier
'taxonomy'=>'product_cat',
'hide_empty' => false
);
wp_reset_postdata();
$child_cats = get_categories( $get_children_cats );//get children of parent category
if(count($child_cats)>0){
echo '<ul class="children">';
foreach( $child_cats as $child_cat ){
//for each child category, get the ID
$childID = $child_cat->cat_ID;
//for each child category, give us the link and name
echo '' . $child_cat->name . '';
wp_reset_postdata();
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $childID,
),
),
);
$loop = new WP_Query($args);
echo "<ul>";
if($loop->have_posts()) {
while ( $loop->have_posts() ) {
$loop->the_post();
// do something
echo "<li> Product Name : ".get_the_title()."</li>";
}
}
echo "</ul>";
}
echo '</ul></li>';
}else{
//$catID
wp_reset_postdata();
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $catID,
),
),
);
$loop = new WP_Query($args);
echo "<ul>";
if($loop->have_posts()) {
while ( $loop->have_posts() ) {
$loop->the_post();
// do something
echo "<li> Product Name : ".get_the_title()."</li>";
}
}
echo "</ul>";
}
} //end of categories logic ?>

Get current Category Name on a page which filters posts by Category and custom meta_key

I'm successfully filtering all my WordPress posts (in a custom page template) by Likes (count) with a Custom Plugin (and meta_key) which also let me filter the most liked posts in a specific category with the following
if (isset($_GET['category'])) {
$args = array(
'meta_key' => '_recoed',
'meta_compare' => '>',
'meta_value' => '0',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'category_name' => sanitize_text_field($_GET['category']),
'paged' => $paged
);
}
query_posts($args);
get_template_part('index');
The Category List to Filter the Posts for each Category (works fine)
<?php $categories = get_categories('exclude=' . implode(',', my_blog_cats()) . ', 1'); ?>
<?php if ($categories) { ?>
<?php $categories = get_categories(); ?>
<?php foreach($categories as $category) { ?>
<li>
<a class="popular-categories" href="<?php echo get_permalink(); ?>?category=<?php echo $category->category_nicename; ?>"><?php echo $category->name; ?></a>
</li>
<?php endforeach; ?>
<?php } ?>
The url after filtering the posts for example - looks like
.../hot-posts/?category=new-posts-category
Any idea how to echo only the current category name on the current page? In the case of the example it would be "New Post Category"
There is 3 possibilities (the taxonomy for WP categories is category):
1) An ID - If $_GET['category'] is a WP category term ID you will use:
if( isset($_GET['category'] ) && term_exists( intval($_GET['category']), 'category' ) ){
$term = get_term( intval($_GET['category']), 'category' );
echo '<p>' . $term->name . '</p>';
}
2) A SLUG - If $_GET['category'] is a WP category term SLUG you will use:
if( isset($_GET['category'] ) && term_exists( sanitize_text_field($_GET['category']), 'category' ) ){
$term = get_term_by( 'slug', sanitize_text_field($_GET['category']), 'category' );
echo '<p>' . $term->name . '</p>';
}
3) A NAME - If it is already a WP category terme NAME just use:
if( isset($_GET['category'] ) && term_exists( sanitize_text_field($_GET['category']), 'category' ) )
echo '<p>' . sanitize_text_field($_GET['category']) . '</p>';
But dont use sanitize_title() on WP category terme NAME as it will become a term SLUG

How to load post titles for each category while loading all categories for a custom post type

I created a custom post type for an FAQ section on my page. I want each category to load as a section title, with the post titles loading below each category.
I am able to load the categories using the following code:
<ul class="sort-by-category">
<?
$args = array(
'orderby' => 'name',
'parent' => 0
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
echo '<li><a class="browse-categories" href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a></li>';
}
?>
</ul>
<?
// Our variables
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;
// grab slug from url
$category_id = get_query_var('cat');
// define args
$args = array(
'posts_per_page' => '36',
'paged' => $page,
'post_type' => 'faqs',
'cat' => $category_id
);
// place args in query
$category_posts = new WP_Query($args);
// our loop
if($category_posts->have_posts()) {
while($category_posts->have_posts()) {
$category_posts->the_post();
get_template_part( 'partials/content', 'browse' );
}
}
wp_reset_query(); ?>
Please help! I'm not great with php

How can I show a list of parent categories and their sub category posts

I need to show lists in this order.. parent-sub-category-title => sub-category-title => sub-category posts. The following code gets me the parent title but doesn't give me the posts. Can anyone tell me why?
parent category title
sub-category title
sub-category-post
//get all categories then display all posts in each term
$taxonomy = 'commongood-categories'; //change this name if you have taxonomy
$param_type = 'category__in';
$term_args=array(
'orderby' => 'name',
'order' => 'ASC'
);
$terms = get_terms($taxonomy,$term_args);
if ($terms) {
foreach($terms as $term){ //this foreach is for top level
if($term->parent == 0){
echo '<h2>'.$term->name.' </h2>'; //get top level category name
$term_args=array(
'orderby' => 'name',
'order' => 'ASC',
'child_of' => $term->term_id
);
$termss = get_terms($taxonomy,$term_args);
foreach( $termss as $terms ) {
$args=array(
"$param_type" => array($terms->term_id),
'post_type' => 'commongood',
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1
);
$my_query = new WP_Query($args);
<?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<li class="series-bubble">
<div class="stext">
<span class="stitle"><?php if(get_field('optional_title')) { echo get_field('optional_title'); } else echo get_the_title(); ?></span>
<span class="scontent"><?php echo get_the_excerpt(); ?></span>
</div>
</li>
<?php endwhile;
}
}
}
}
You'll have to use a tax_query arg for custom taxonomies, category__in only works for categories: http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
Also, caller_get_posts has been deprecated for a while, use ignore_sticky_posts instead.

WORDPRESS Simple Query

I have a category query, and in my category query I want to get product (only one) by queried category id (or name or whatsoever)
I start query:
<?wpsc_start_category_query(array('category_group'=> get_option('wpsc_default_category'))); ?>
and then try to use get_posts() function to get product:
$args = array(
'post_type' => 'wpsc-product',
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'wpsc_product_category',
'field' => 'id',
'terms' => $aka
)));
$cat1_posts = get_posts($args);
where $aka is:
$aka = '[wpsc_category_id]';
but when I echo $cat1_posts[0]->ID; it only shows my last product ID for every category. what is the problem? echoing only [wpsc_category_id] works perfect.
I tried EVERYTHING for the last few days. I will buy you cookies for help
I've got to idea, that I need foreach or anything like this
You can use the get_terms() function. So something like this (untested)
<?php
//for each category, show latest post
$cat_args=array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_terms( 'wpsc_product_category');
foreach($categories as $category) {
$args=array(
'showposts' => 1,
'post_type' => 'wpsc-product',
'wpsc_product_category' => array($category->slug)
);
$posts=get_posts($args);
if ($posts) {
echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
foreach($posts as $post) {
setup_postdata($post); ?>
<p><?php the_title(); ?></p>
<?php
} // foreach($posts
} // if ($posts
} // foreach($categories
?>

Categories