related products on woocommerce - wordpress

i have next loop:
<?php woocommerce_product_loop_start(); ?>
<?php
// Setup your custom query
$args = array('post_type' => 'product','posts_per_page' => '4','orderby' => 'rand');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
From some reason that's display always the same 4 products. what i want is - that on every refresh it will display differents products from all categories i have on WooCommerce.
What i need to add to the loop, or should i need to create something else for that?

it might be a conflict with plugin. Some plugins disable ability for random ordering unless you filter it out with: remove_all_filters('posts_orderby');.
So try to put that before your query:
<?php
remove_all_filters('posts_orderby');
// Setup your custom query
$args = array('post_type' => 'product','posts_per_page' => '4','orderby' => 'rand');
$loop = new WP_Query( $args );

Related

Display Random Product Link

I need PHP-code for WordPress (Woocommerce) to display random product link.
For example, I have Product1 and want to display on this page (in description of my product):
"See also other products: [Product2 - link] and [Product3 - link]"
Don't know how, I just need php code to insert it in post/pages/products and everywhere I want on my site.
I'm not a coder and I found this code, for example, to display page title with link, but it's not what I need
<?php
echo ''.get_the_title($product_id).'';
?>
But how to get random product, don't know, thanks for help.
Try this :
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'post_type' => 'product' );
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<?php the_title(); ?>
<?php endforeach;
wp_reset_postdata();
The Perfect solution for outputting a single random product which can be achieved using the following code.
<?php
$post_array=array();
$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();
array_push($post_array,get_the_ID());
endwhile;
$random_key = array_rand($post_array, 1);
echo ''.get_the_title($post_array[$random_key]).'';
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
Have tested the same for you. It worked. Lemme Know if the same worked for you too.

How to not repeat wordpress loop/query?

This is a bad habit i've been using in wordpress and i want to stop. I repeat the loop/query code when i should fetch all at once. Here is an example...
<?php
$args = array(
'p' => 9345, // id of a page, post, or custom type
'post_type' => 'front page content');
$loop = new WP_Query( $args );
//Display the contents
while ( $loop->have_posts() ) : $loop->the_post();
the_content();
endwhile;
$args = array(
'p' => 9341, // id of a page, post, or custom type
'post_type' => 'front page content');
$loop = new WP_Query( $args );
//Display the contents
while ( $loop->have_posts() ) : $loop->the_post();
the_content(); endwhile;
?>
If i want to display the content of the id 9345 first and the content of the id 9341 second, how do i do this all without duplicating WP_Query? I know about order_by but what if i want to specifically order results from the query?
You can use post__in, Read more
<?php
$args = array(
'post__in' => array(9345, 9341),
'post_type' => 'page'
)
$loop = new WP_Query( $args );
//Display the contents
while ( $loop->have_posts() ) : $loop->the_post();
the_content();
endwhile;
//DONT FORGET THIS
wp_reset_postdata();
?>

Target custom field type plugin value using WP_Query

In wordpress, using the CTU plugin, I made a custom post type called apartments with a field called available. I only want to target any post with available=yes. How would I do this? I tried the_post('available=yes')
<?php
$args = array(
'post_type' => 'apartment'
);
$the_query = new WP_Query( $args );
?>
<?php if( have_posts()): ?>
<?php while ($the_query->have_posts()): ?>
<?php $the_query->the_post(); ?>
<?php $the_field('available'); ?>
<?php endwhile; ?>
<?php else: ?>
<?php endif; ?>
i think the simplest solution is:
1. In your custom taxonomy create a term called available
2. add this to your custom query
$args = array(
'post_type' => 'apartment',
'category_name' => 'available'
);

Making custom WooCommerce loop

I'm using already designed theme for wordpress, and now instead of regular blog posts I would like to display WooCommerce products (which are custom post types I persume).
This is the current query with display loop:
<?php
$args = array(
//'posts_per_page' => '2',
'paged' => get_query_var('paged')
);
$homepage_query = new WP_Query($args);
?>
<?php //query_posts('posts_per_page=4&paged='.get_query_var('paged')); ?>
<?php if ( have_posts() ) : ?>
<?php while ( $homepage_query->have_posts() ) : $homepage_query->the_post(); ?>
<?php if($style == 'blog_style') { ?>
<div id="blog-style" class="post-box">
<?php get_template_part('content', 'blog'); ?>
</div>
<?php } else { ?>
<div class="post-box grid_4 <?php aero_post_box_class(); ?>">
<?php get_template_part('content', ''); ?>
</div>
<?php } ?>
<?php endwhile; ?>
Is there a way to add options to $args so the loop displays WooCommerce products? I'm also using pagination with this loop, which is required on this project, so that's why it's important to use this loop.
You should be able to access products through the loop, setting the post_type arg to product:
<?php
// Setup your custom query
$args = array( 'post_type' => 'product', ... );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php echo get_permalink( $loop->post->ID ) ?>">
<?php the_title(); ?>
</a>
<?php endwhile; wp_reset_query(); // Remember to reset ?>
This is the proper way to re-create and customize the WooCommerce product loop:
if(!function_exists('wc_get_products')) {
return;
}
$paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1; // if your custom loop is on a static front page then check for the query var 'page' instead of 'paged', see https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters
$ordering = WC()->query->get_catalog_ordering_args();
$ordering['orderby'] = array_shift(explode(' ', $ordering['orderby']));
$ordering['orderby'] = stristr($ordering['orderby'], 'price') ? 'meta_value_num' : $ordering['orderby'];
$products_per_page = apply_filters('loop_shop_per_page', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page());
$products_ids = wc_get_products(array(
'status' => 'publish',
'limit' => $products_per_page,
'page' => $paged,
'paginate' => true,
'return' => 'ids',
'orderby' => $ordering['orderby'],
'order' => $ordering['order'],
));
wc_set_loop_prop('current_page', $paged);
wc_set_loop_prop('is_paginated', wc_string_to_bool(true));
wc_set_loop_prop('page_template', get_page_template_slug());
wc_set_loop_prop('per_page', $products_per_page);
wc_set_loop_prop('total', $products_ids->total);
wc_set_loop_prop('total_pages', $products_ids->max_num_pages);
if($products_ids) {
do_action('woocommerce_before_shop_loop');
woocommerce_product_loop_start();
foreach($products_ids->products as $featured_product) {
$post_object = get_post($featured_product);
setup_postdata($GLOBALS['post'] =& $post_object);
wc_get_template_part('content', 'product');
}
wp_reset_postdata();
woocommerce_product_loop_end();
do_action('woocommerce_after_shop_loop');
} else {
do_action('woocommerce_no_products_found');
}
Using the code above, you would customize the wc_get_products() arguments to get the IDs of the products you want (if you have specific criteria). Once that code is in place, all the features of a native WooCommerce loop will be available to you—pagination, ordering, etc. This method is superior to WP_Query and get_posts() because those two methods can break.
I've written a more detailed blog post about custom WooCommerce loops here: https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/
You can Also get Category using thi code
$terms = get_terms('product_cat');
foreach ($terms as $term) {
$term_link = get_term_link( $term, 'product_cat' );
echo '<li>' . $term->name . '</li>';
}
If You want only parent category then
wp_list_categories('taxonomy=product_cat&orderby=order&title_li=&depth=1');

Combine 2 Wordpress While Statements in Loop

I want to only show posts on a wordpress page that belong to logged in users AND contain a custom meta key "color." I have the code for each option i.e. I can either show posts belonging to logged in users or posts with a meta key = color but I cant work out how to combine both so both conditions need to be true. Below are the 2 pieces of code i'm working with:
<!-- If Logged In -->
<?php
if ( is_user_logged_in() ):
global $current_user;
get_currentuserinfo();
$author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
$author_posts = new WP_Query($author_query);
while($author_posts->have_posts() : $author_posts->the_post();
get_template_part( 'content', 'page', 'the_meta()' );
?>
<!-- If Posts Contains Color Meta -->
<?php
$the_query = new WP_Query('meta_key=color');
while ($the_query->have_posts() ) : $the_query->the_post();
endwhile;
?>
Does anyone know how to combine them so posts that match both conditions are shown?
Something like this should work:
<?php
if ( is_user_logged_in() ) :
global $current_user;
get_currentuserinfo();
$query = array('posts_per_page' => '-1','author' => $current_user->ID, 'meta_key' => 'color');
$result = new WP_Query($query);
while ($result->have_posts()) : $result->the_post();
get_template_part( 'content', 'page', 'the_meta()' );
endwhile;
endif;
?>

Resources