Ecommerce Shopify WordPress Discussion

Loop through categories and posts of a custom post type in WordPress?

I've created a custom post type called faq in WordPress and I've created a few categories for it - like "Billing" and "Shipping". My end goal is to create multiple FAQ "Posts" so I can add them to our search API. However, I'm stuck on trying to loop through the post categories and display the FAQ's under each category if the category has FAQ posts: Here's my code: $category_args = array( 'orderby' => 'name', 'order' => "ASC", ); $categories = get_categories( $category_args ); // Get all Categories foreach ( $categories as $category ) { $post_args = array( 'post_type' => 'faq', 'post_status' => 'publish', 'numberposts' => -1, ); $posts = get_posts( $post_args ); // Get all FAQ post_types from categories // Here's where I'm getting stuck: If a category has faq posts: // 1.) Display the category title // 2.) Loop through the posts } Any ideas on how to modify this code to output like so: // Billing // - Billing Question 1 // - Billing Question 2 // Shipping // - Shipping Question 1 // - Shipping Question 2 etc.
I had similar code, but with custom categories as well. So lets first try this adaption of code which works with regular posts and categories. The trick is to use WP_Query function, while not forgetting to wp_reset_query() afterwards. $category_args = array( 'orderby' => 'name', 'order' => "ASC", ); $categories = get_categories($category_args); // Get all Categories foreach ($categories as $category) { // $post_args = array( // 'post_type' => 'faq', // 'post_status' => 'publish', // 'numberposts' => -1, // ); $args = array( 'cat' => $category->term_id, // 'post_type' => 'faq', // maybe? 'posts_per_page' => -1, ); $posts = new WP_Query($args); if ($posts->have_posts()) { echo "<h1>" . $category->name ."</h1>"; while ($posts->have_posts()) { $posts->the_post(); echo "<h2>" . get_the_title() . "</h2>"; } } wp_reset_query(); }

February 26, 2024

TurboCommerce make the better internet purchasing globaly

Turbo Multi-language Translator

Make the better internet purchasing globaly

Turbosify SEO Speed Booster

5.0 (7) Free plan available
Get better conversions by improving store loading speed Installed

Turbo Multi-language Chat - AI Customer service in one hand

TurboCommerce make the better internet purchasing globaly
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.