I'm currently showing the products of one WooCommerce product category (events) with the following code:
<?php $args = array( 'post_type' => 'product', 'product_cat' => 'events');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
Is it possible to get a product category by name instead of slug or ID?
Since I'm using a translation plugin (WPML) slugs have been added per language (for example "events_eng").
Thanks.
You could use another trick is to get the language extension used by WPML in the category slug and then to add it to your slug, this way:
<?php
// Set here your category slug
$cat_slug = 'events';
// Get the current language
$lang = explode("-", get_bloginfo('language'));
// Adding the language extension to the slug
$cat_slug .= '_' . $lang[0];
$args = array( 'post_type' => 'product', 'product_cat' => $cat_slug);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
?>
If for the main language you don't have a language extension in the category slug, you can add a condition in this code to avoid adding it to this particular language.
This code is tested and it's fully functional.
Related
How do I output selected products from a Woocommerce Plugin so the list looks the same as a product category list?
Woocommerce has a built-in shortcode [products] to output products. I can do that if I create a page, but can I do that programmatically?
e.g. URL is /prods/?custom_key=test (I know how to tell WP to recognise the URL and use my code)
Using WP_Query I set global $wp_query to returns a list of products to be outputted.
global $wp_query
$args = [...];
$wp_query = new WP_Query( $args );
I've tried using the archive page
include(get_query_template('archive'));
which almost works, but it doesn't display the products like it would in a product category.
After creating $wp_query, how do I output the products by re-using the product loop that the shortcode [products] would use?
This is a simple product loop that you can use in any template file
<ul class="products">
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</ul><!--/.products-->
this utilizes Woocommerce template structure as the shortcode would. you can change your args to what ever you need to pull through
I want to display in the article sidebar (in wordpress) a list of 5 recent articles from that category to which it belongs. I'm using the code below to (using a shortcode) show the 5 posts (from category 62 in this case). Is there a way to write this code in functions.php so that it is optimised, and I don't have to rewrite everything for each new category?
/**
* function to add recent posts widget
*/
function wpcat_postsbycategory_musculacao() {
// the query
$the_query = new WP_Query( array( 'cat' => '62', 'posts_per_page' => 5 ) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbytag widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '' . get_the_post_thumbnail($post_id, array( 80, 80) ) . get_the_title() .'</li>';
} else {
// if no featured image is found
$string .= '<li>' . get_the_title() .'</li>';
}
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts-musculacao', 'wpcat_postsbycategory_musculacao');
/**
* function to change search widget placeholder
*/
function db_search_form_placeholder( $html ) {
$html = str_replace( 'placeholder="Pesquisar ', 'placeholder="Buscar ', $html );
return $html;
}
add_filter( 'get_search_form', 'db_search_form_placeholder' );
The complication here is that in WP a post can have multiple categories. You need to decide how to handle that - get from all categories, or if you only want to show posts from one category, how do you choose which?
I've given a few answers below depending on how you want to handle that.
1. Get posts in any of the categories of the current post
As posts can have multiple categories, you can get all of the ids and use this to query for posts that are in any of those categories:
// 1. get the categories for the current post
global $post;
$post_categories = get_the_category( $post->ID );
// 2. Create an array of the ids of all the categories for this post
$categoryids = array();
foreach ($post_categories as $category)
$categoryids[] = $category->term_id;
// 3. use the array of ids in your WP_Query to get posts in any of these categories
$the_query = new WP_Query( array( 'cat' => implode(",",$categoryids), 'posts_per_page' => 5 ) );
1a. Get posts in any of the categories but not their children
Note cat will include children of those category ids. If you want to include those exact categories only and not children, use category__in instead of cat:
$the_query = new WP_Query( array('category__in' => $categoryids, 'posts_per_page' => 5) );
2. Get posts that have all of the categories of the current post
If you want posts that have all the same categories as the current one, this is done in the same way as above, except we use category__and instead of cat (Note that this does not include children of those categories) :
$the_query = new WP_Query( array('category__in' => $categoryids, 'posts_per_page' => 5) );
3. If you know your post will only have one category
If you know you only have one category per post, then you can just use the first element from the category array:
// 1. Just use the id of the first category
$categoryid = $post_categories[0]->term_id;
$the_query = new WP_Query( array( 'cat' => $categoryid, 'posts_per_page' => 5 ) );
4. Pass the category into the shortcode
If you want to specify which category to show, you can pass the category id into the shortcode, letting you choose whichever category you want. (FYI you can also get it to work with slug instead of id, which might be a bit more user-friendly)
Your shortcode is currently used like this, I assume:
[categoryposts-musculacao]
We can change the function so you can pass the category like this:
[categoryposts-musculacao category=62]
Shortcode function can accept an $attributes argument that has the information or "attributes" we're adding to the shortcode, e.g. category. We use this to get the category passed in as a variable called $category and then just use it instead of the hardcoded value in the rest of your function.
// 1. include the $attributes argument
function wpcat_postsbycategory_musculacao( $attributes ) {
// 2. get the value passed in as category - this will save it into a variable called `$category`
extract( shortcode_atts( array(
'category' => ''
), $attributes ) );
// 3. if there is no category don't do anything (or sohw a message or whatever you want
if (!$category) return "";
// 4. Now just use your variable instead of the hardcoded value in the rest of the code
$the_query = new WP_Query( array( 'cat' => $category, 'posts_per_page' => 5 ) );
// do the rest of your stuff!
}
Reference: Wordpress Codex Shortcode API
4a. Pass the category into the shortcode by slug
If you want the category attribute in your shortcode to work with a slug instead of the id, you just need to change WP_Query to use category_name instead of cat:
$the_query = new WP_Query( array( 'category_name' => $category, 'posts_per_page' => 5 ) );
I would like to ask how is it possible when i have 3000 variable products in an old woocommerce version eshop, when i am trying to loop throught them that i get only 300 in return instead.
The following code is used by me in order to generate a product feed.
$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
Also the variable products are called variable because they support variation as I understand. That means that 3000 variable products are not 3000 "normal" products and instead the 300 that I see is the correct number of them?
May be you are mixing up products (simple or variable) and product variations (that remain to variable products)... You need to display products (simple and variable) in your WP_Query, but not your product variations.
With 'post_type' => 'product', you will get simple and variable products at the same time.
The missing argument is posts_per_page to be set to -1.
So your code will be:
$args = array( 'post_type' => 'product', 'posts_per_page' => -1);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) :
$loop->the_post();
// set all product IDs in an array
$all_product_ids[] = $loop->post->ID;
endwhile;
// Testing: Output the number of products in that query
echo '<p>Products count: ' . count($all_product_ids) . '</p>';
Then you will get all your products.
May be you can try to use a WPDB query:
## --- THE SQL QUERY --- ##
global $wpdb;
$table_name = $wpdb->prefix . "posts";
$product_ids_array = $wpdb->get_col("
SELECT `ID`
FROM `$table_name`
WHERE `post_status` LIKE 'publish'
AND `post_type` LIKE 'product'
");
## --- TESTING OUTPUT --- ##
// Testing raw output of product IDs
print_r($product_ids_arr);
// Number of products
$products_count = count($product_ids_arr);
echo '<p>Products count: '. $products_count. '</p>';
## --- THE LOOP --- ##
foreach ($product_ids_array as $product_id):
// Get an instance of WP_Product object
$product = new WC_Product($product_id);
// Use the WP_Product methods to get and output the necessary data
endforeach;
I have a custom post type advice and taxonomy adcat. I want to display all post belong to that category.
Lets say I have 4 categories namely : 'games', 'tours', 'dishes', 'hotels' and also this four category is a menu. If I click one of the category for example: hotels all post belong to the hotels should display.
By the way this code I used to show wordpress default categories:
<?php $catname = wp_title('', false); ?>
<?php $posts = get_posts("category_name=$catname&numberposts=8&offset=0");
foreach ($posts as $post) : start_wp(); ?>
//html output
<h1><?php the_title(); ?></h1>
<?php endforeach; ?>
this is not working in custom post 'taxonomies' any suggestion would be helpful thank's
try this maybe it work... I write a note so you can see whats going on.. hope it help
<?php
// Get the term/category of the post
$terms = get_the_terms( $post->ID , 'advice-cat' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'advice cat' );
}
//WordPress loop for custom post type
$terms = get_the_terms( $post->ID , 'advice-cat' );
$my_query = new WP_Query('post_type=advice&advice-cat=' . $term->name . '&posts_per_page=-1');
while ($my_query->have_posts()) : $my_query->the_post(); ?>
// output content
<?php the_title(); ?>
<?php endwhile; wp_reset_query(); ?>
try something like this, this is the example to fetch post by category id
$args = array( 'cat' => $cat_id, 'post_type' => 'advice', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
endwhile;
wp_reset_postdata();
you can also use with category name as well.
$args = array('category_name' => 'catname', 'post_type' => 'advice', 'posts_per_page' => -1 );
you can use post_per_page as per your requirement, I have just added -1 for all the posts
I don't really understand your terminology. When you are talking about adcat, is it a custom taxonomy or a term of the build-in taxonomy category. If adcat is a custom taxonomy, you should use the tax_query in WP_Query,not the category parameters.
Remember, category and a custom taxonomy are both taxonomies, their direct children is called terms, and their direct childen is called child terms
You should also not be using wp_title() to get the queries object. You should be using get_query_var() to get the queried object. For categories it will be cat, taxonomy will be taxonomy and for terms term. Have a look at get_categories, get_taxonomies and get_terms for returned values
Example
$category = get_query_var( `cat` );
$cat_slug = $category->slug;
You can now return $cat_slug to your custom query as category_name
EDIT
I've quickly rethinked the whole thing and checked your comment as well. Why not just copy your index.php and rename it taxonomy.php. There is no need at all for a custom query here. The default loop in taxonomy.php should do it
EDIT 2
For further reading, go and check the following articles
Theme Development
Template Hierarchy
Not sure if I read your answer correctly but what I am assuming is you want to search posts by the taxonomy terms correct? So in your adcat taxonomy you have 'games', 'tours', 'dishes', 'hotels' as your terms or categories. Your best option would be to use a tax_query in your query arguments. Here is how to do that with the WP_Query() object.
<?php
$args = array(
'post_type' => 'advice',
'posts_per_page' => 8,
'tax_query' => array(
'taxonomy' => 'adcat',
'terms' => array('games', 'tours', 'dishes', 'hotels'),
'field' => 'slug'
)
);
$query = new WP_Query($args);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>
Important Note:
When using a WP_Query you will be overwriting the default post data. So in order to get that data back you just use the wp_reset_postdata() as you can see in the example above after the loop has finished.
I am currently working on a personal project and the this page basically has two tabs each will display the archive for specific categories under one custom post type called webinar.
I am calling the category in one of the tabs using
<?php query_posts('category_name=demos-on-demand-videos'); ?>
However when i do this i' just getting the no post's found screen, what am i doing wrong? I am trying to display the post archive from the category demos-on-demand-videos which is under the webinar custom post type.
use this
query_posts( array( 'post_type' => 'webinar','your-custom-taxnomy' => 'demos-on-demand-videos' ) );
while ( have_posts() ) :
the_post();
$post_id = $post->ID;
endwhile;
Follow this link:
http://eyan16.wordpress.com/2013/09/16/how-to-fetch-posts-from-custom-posts-type-with-custom-taxonomy/
Make a page template for each of your tabs and use this custom loop in it. Make sure to adjust it for your specific post type, taxonomy, or term.
<?php $args=array(
'post_type' => 'webinar', //set the post_type to use.
'taxonomy' => 'demos-on-demand-videos', // set the taxonomy to use.
'term' => 'term1', //set which term to use or comment out if not using.
'posts_per_page' => 10 // how many posts or comment out for all.
);
$webinarloop = new WP_Query($args);
if($webinarloop->have_posts()) : while($webinarloop->have_posts()) :
$webinarloop->the_post();
get_template_part( 'content' ); //or whatever method you use for displaying your content.
endwhile; endif; //end the custom post_type loop
?>
This code works for me just fine
* x is taxonomy name name you have created
* y is category slug
$args = array('post_type' => 'client','posts_per_page'=>'8','order'=>'DESC','x'=>'y');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();