Making custom WooCommerce loop - wordpress

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');

Related

How to get taxonomy in a div

I want to add a taxonomy in my div with the different other fields, but I'm new to wordpress and O don't find how doing this, if someone can help me please ?
<?php/* Template Name: Archive Projets */ ?>
<?php get_header(); ?>
<?php
$posts = get_posts(array(
'posts_per_page' => 4,
'post_type' => 'projects'
));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post );
?>
<div>
<?php the_title(); ?>
<div><?php the_field('url')?></div>
<div><?php the_field('')?></div> /* HERE I WANT TAXONOMY */
</div>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
Here's a code that will get the taxonomies of the current post and display them in a list of insert this code under <div><?php the_field('url')?></div>
// Get all terms
$terms = get_the_terms( $post->ID , array( 'Taxonomy_name') );
// Dispaly the taxonomies, if there one or more.
foreach ( $terms as $term ) {
echo '<div>' . $term->name . '</div></br>';
}
Make sure to change the 'Taxonomy_name' with your taxonomy name. let me know if I got you wrong or if you need any help with the code.
A quick google search brings up get_terms().
$terms = get_terms( array(
'taxonomy' => 'post_tag',
'hide_empty' => false,
) );
foreach($terms as $current_term) {
//You can now loop through them and get the ones you want, display them all, or whatever else it is you want to do. Note: each $current_term is an object of type WP_Term (or error if there are no results).
}

display wp custom posts by catgeory

Added this code to display wp custom post by category, but unable to get pagination to work when added posts_per_page="5"
<?php query_posts('post_type=encounters_news'); while (have_posts()) : the_post(); ?>
<?php $terms = get_the_terms($post->ID, 'encounters_news_categories');
foreach($terms as $item):
if($item->slug == "chapter-news"):?>
<?php get_template_part( 'content-news', 'page' ); ?>
<?php //comments_template( '', true ); ?>
<?php endif; ?>
<?php endforeach; ?>
<?php endwhile; wp_reset_query(); ?>
<?php encounters_content_nav( 'post-nav' ); ?>
Rewrote and change to this code
<?php
// set up or arguments for our custom query
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$post_type = 'encounters_news';
$tax = 'chapter-news';
$tax_terms = get_terms($tax);
if ($tax_terms) {
foreach ($tax_terms as $tax_term) {
$query_args = array(
'post_type' => $post_type,
'$tax' => $tax_term->slug,
'showposts' => 5,
'paged' => $paged
); wp_reset_query();
}}
// create a new instance of WP_Query
$the_query = new WP_Query( $query_args ); ?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); // run the loop ?>
<?php get_template_part( 'content-news', 'page' ); ?>
<?php endwhile; ?>
<?php if ($the_query->max_num_pages > 1) { // check if the max number of pages is greater than 1 ?>
<div class="navigation">
<div class="alignleft"><?php echo get_previous_posts_link( '« Previous' ); // display newer posts link ?></div>
<div class="alignright"><?php echo get_next_posts_link( 'More »', $the_query->max_num_pages ); // display older posts link ?></div>
This code creates the pagination as desired, but displays all the Encounters News Categories instead of just the Chapter News category.
Suggestions will be greatly appreciated.
Resolved
<?php
$query = new WP_Query( array(
'post_type' => '', // name of post type.
'tax_query' => array(
array(
'taxonomy' => '', // taxonomy name
'field' => '', // term_id, slug or name
'terms' => , // term id, term slug or term name
)
),'showposts' => 5,
'paged'=>$paged
) );
while ( $query->have_posts() ) : $query->the_post();
// do stuff here....
endwhile;
/**
* reset the orignal query
* we should use this to reset wp_query
*/
wp_reset_query();?>

Wordpress - page as category

I researched several tutorials and nothing ...
can someone tell me how do I print only the category "news" in the article page?
Theme Onepress*
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', 'list' );
?>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
Maybe the easiest way is to create your own query:
// WP_Query arguments
$args = array (
'post_type' => array( 'news' ),
'post_status' => array( 'publish' ),
'posts_per_page' => '-1',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
This gives you all the query results that are: published and of the 'news' custom post type.
// WP_Query arguments
$args = array (
'post_status' => array( 'publish' ),
'category_name' => 'news',
'posts_per_page' => '-1',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
The second one gives you all the query results, that are published and in the category 'news'.

get_the_title() is returning results from previous loop

I'm attempting to loop thought a custom post type (artists), then each category, then another custom post type (story) which has a relationship with the artist.
The issue is, the function <?php echo get_the_title( $story->ID ); ?> in the final loop is returning a title of the Artist many times over, along with the title of the current custom post. I just need the title of the currentent loops post.
<!-- get all the artists -->
<?php
$args = array(
'post_type' => 'artists'
);
$query = new WP_QUERY( $args );
?>
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<p><?php the_field('artist_website'); ?></p>
<!-- looping through all the categories -->
<?php
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
// Make a header for the cateogry
echo "<h2>".$cat->name."</h2>";
?>
<!-- looping through the stories that have a relationship with the artist (select_artist) -->
<?php
$post_type = 'story';
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1, //show all posts
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $cat->slug,
)
),
'meta_query' => array(
array(
'key' => 'select_artist', // name of custom field
'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123.
'compare' => 'LIKE'
)
)
);
$stories = new WP_Query($args);
?>
<?php if( $stories ): ?>
<ul>
<?php foreach( $stories as $story ): ?>
<!-- Problem echo below -->
<?php echo get_the_title( $story->ID ); ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php } // done the foreach statement ?>
<?php endwhile; wp_reset_postdata(); endif; ?>
</section>
If you're using WP_Query you should be using a while loop and end with the_post() in order to set up the internal variables that would allow get_the_title() to work properly.
As an added measure you could set the $post variable to a $temp variable before your inner loop, then reset back after.
<?php
$stories = new WP_Query($args);
if( $stories->have_posts() ):
global $post;
$temp = $post;
?>
<ul>
<?php
while( $stories->have_posts() ): $stories->the_post();
the_title();
endwhile;
$post = $temp;
?>
<ul>
<?php endif; ?>

Wordpress - Grab Item by Category in Post Type Query

I have setup a custom post type in Wordpress. It is a section where the client can upload documents in PDF format. The documents are divided into two categories - 'Downloadable Forms' and 'Menu' ; the Custom Field name for the category is 'document_category'
I am trying to run a query and only display the 'Downloadable Forms' on a page. Here is the code I normally use --- I'm hoping someone can help me add what I need to make it work?
<?php
$args = array('post_type' => 'prep_forms', 'posts_per_page' => -1);
// The Query
$the_query = new WP_Query( $args );
// The Loop
$i = 0;
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<li><?php the_title(); ?></li>
<?php
$i++;
endwhile;
// Reset Post Data
wp_reset_postdata();
?>
Thanks.
<?php
$args = array('post_type' => 'prep_forms', 'posts_per_page' => -1);
// The Query
$the_query = new WP_Query( $args );
// The Loop
$i = 0;
while ( $the_query->have_posts() ) :
$the_query->the_post();
// Get all Advanced custom fields
$my_custom_fields = get_fields(get_the_ID());
// Does document_category field exists and is it equal with 'Downloadable Forms'?
if(isset($my_custom_fields['document_category']) && $my_custom_fields['document_category'] == 'Downloadable Forms'):
?>
<li><?php the_title(); ?></li>
<?php
endif;
$i++;
endwhile;
// Reset Post Data
wp_reset_postdata();
?>
I've used the get_fields($post_id = false) function of the Advanced Custom Fields plugin that returns an array of all the posts' custom fields and then filtered it to match your needs.
Hope i've helped
Well, you can use the is_category(); inside loop and only display those posts, like so (using your same code):
<?php
$args = array('post_type' => 'prep_forms', 'posts_per_page' => -1);
// The Query
$the_query = new WP_Query( $args );
// The Loop
$i = 0;
while ( $the_query->have_posts() ) : $the_query->the_post();
if(is_category('Sownloadable Forms')){ // here the condition
?>
<li><?php the_title(); ?></li>
<?php
$i++;
} // here ends the IF statment
endwhile;
// Reset Post Data
wp_reset_postdata();
?>
Better yet: http://codex.wordpress.org/Function_Reference/is_category
Hope that helps.
Why dont you make it simpler and set a query based on custom field data?
<?php
$count = 1;
$args = array(
'post_type' => 'any',
'posts_per_page' => 4,
'meta_key' => 'display',
'meta_value' => 'true'
);
$query = new WP_Query();$query->query($args);
while ($query->have_posts()) : $query->the_post();
$do_not_duplicate[] = $post->ID;
?>
<!-- query content -->
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php printf( esc_attr__( 'Permalink to %s', 'advanced' ), the_title_attribute( 'echo=0' ) ); ?>" ></h2>
<?php the_excerpt() ;?>
<!-- query content -->
<?php $count++; endwhile; wp_reset_query(); ?>
That way any post with custom field key display and custom field value true will be shown on your query.

Resources