WordPress Adding Variables to Loop Arguments - wordpress

I have a custom post-type call Called 'Sectors' and another post type called 'Challenges' The challenges post type has a taxonomy called 'sectortype' - which has the same names as the sectors.
I created a page called 'single-sector.php' On that page displays a loop that includes challenges related to that sector.
When I write the loop for displaying challenges, how do I make the 'sectortype' => 'advanced-education' a variable so it will work on other single sector pages?
Here's what I have for the loop...
<?php $challenge_args = array(
'post_type' => 'challenge',
'sectortype' => 'advanced-education', //Need Help Here
);
// create a new instance of WP_Query
$challenge_query = new WP_Query( $challenge_args );
?>
<?php if ( $challenge_query->have_posts() ) : while ($challenge_query->have_posts() ) : $challenge_query->the_post(); // run the loop ?>

Get Custom posts by custom taxonomy terms :
<?php
$terms = get_terms('sectortype');
$challenge_args = array(
'post_type' => 'challenge',
'publish_status' => 'published',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'sectortype',
'field' => 'slug',
'terms' => $terms[0], //whichever term you want to select
),
),
);
// create a new instance of WP_Query
$challenge_query = new WP_Query( $challenge_args );
?>
<?php if ( $challenge_query->have_posts() ) : while ($challenge_query->have_posts() ) : $challenge_query->the_post(); // run the loop ?>
DISPLAY IN SEPARATE PAGES
TO display the posts in separate pages as you mentioned in the comment, you have to do the following:
Create Separate Page Links:: (use on page as navigation items)
<?php $categories = get_terms('sectortype');?>
<ul>
<?php foreach( $categories as $key => $c ):?>
<?php $cat_link = get_term_link( $c->term_id );?>
<?php $term_title= single_term_title('', false);?>
<li class="<?php echo ($c->name == $term_title )?'active':'';?>"><?php echo $c->name;?></li>
<?php endforeach;?>
</ul>
Create a file in theme directory (actually an archive template for taxonomy terms) with the filename 'taxonomy-sectortype.php'.
On that template, get the posts from the usual loop without using any queries and you will get the respective posts.

Related

Why wc_get_template_part() not working inside wc_get_products()?

Cant find full loop example on the web with wc_get_template_part() and wc_get_products(), so looking for help here:
global $woocommerce;
global $product;
$args = array(
'limit' => 15,
'category' => array('printers', 'laptop')
);
$query_cats = wc_get_products($args);
foreach ($query_cats as $query_cat) {
echo $query_cat->get_id();
echo $query_cat->get_title();
// echo "<pre>";
// var_dump($query_cat);
wc_get_template_part('content', 'product');
}
?>
Titles and ids are displayed, var_dump also, bu wc_get_template_part - no. I have add_theme_support('woocommerce'); and also body_class();
WooCommerce content-product.php template only works only with standard loop(with instance of Wp_Query). May be following solution can help:
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'tax_query' => [
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => ['printers', 'laptop'],
)
],
);
$product = new WP_Query( $args );
while ( $product->have_posts() ) {
$product->the_post();
wc_get_template_part( 'content', 'product' );
}
wp_reset_postdata();
Thanks
Yes, it can be done (2022 update)
If you want to avoid native WP_Query or using shortcodes, this actually can be done using wc_get_products().
You just need to setup and reset postdata within your foreach loop and setup WooCommerce loop properly.
global $post; // Do not forget this!
$args = array(
'limit' => 15,
'category' => array('printers', 'laptop')
);
$products = wc_get_products( $args );
// Set loop properties
wc_set_loop_prop('columns', 5);
// Start custom WC loop
woocommerce_product_loop_start();
foreach( $products as $product ) {
// Setup postdata
$post = get_post( $product->get_id() );
setup_postdata( $post );
// Get template part
wc_get_template_part( 'content', 'product' );
}
// End loop and reset postdata
woocommerce_product_loop_end();
wp_reset_postdata();
Important note: this will only work if queried products are within any HTML element with the woocommerce class (otherwise WooCommerce CSS won't load for your products). In some templates, the woocommerce class is already part of the DOM (e.g. <body> element), but if it isn't, wrap your loop within an element as such:
<div class="woocommerce my-products-loop">
<?php // Your loop goes here ?>
</div>
TIP: You can set various loop properties using wc_set_loop_prop in the "Set loop properties" part of the code

WordPress: All posts are rendering instead of rendering only assigned taxonomy posts on taxonomy page

I have a products post type and it has a various categories. Currently there are around fifty plus posts assigned to different categories. Note: I am using a custom taxonomy called product_categories.
Scenario:
I have a category named food-products and it has a sub categories as chocolates, dairy, grocery.
Now when user goes to the category page eg site.com/product-category/food-products at that time all other categories posts are also displaying but when i click on the sub category tabbing menu at that time it displays the correct assigned sub category posts
So, my question is how can the only the respected category of subcategory posts will be displayed on page load ?
<?php $loop = new WP_Query(array('post_type' => 'product', 'posts_per_page' => -1));
$count =0; ?>
<div class="row portfolio-container">
<?php if ( $loop ) : while ( $loop->have_posts() ) : $loop->the_post();
$url = get_the_post_thumbnail_url( $post_id, 'thumbnail_size' );
$terms = get_the_terms( $post->ID, 'product_categories' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
foreach ( $terms as $term ) { $links[] = $term->name; }
$links = str_replace(' ', '-', $links);
$tax = join( " ", $links );
else :
$tax = '';
endif; ?>
<div class="col-lg-4 col-md-6 portfolio-item <?php echo strtolower($tax); ?>">
<div class="portfolio-wrap">
<img src="<?php echo $url;?>" class="img-fluid" alt="">
<div class="portfolio-info">
<h4><?php the_title();?></h4>
<div class="portfolio-links">
<i class="ion ion-eye"></i>
<i class="ion ion-android-open"></i>
</div>
</div>
</div>
</div>
<?php endwhile;?>
<?php wp_reset_query();?>
<?php endif;?>
</div>
JQuery:
$(window).on('load', function () {
var portfolioIsotope = $('.portfolio-container').isotope({
itemSelector: '.portfolio-item'
});
$('#portfolio-flters li').on( 'click', function() {
$("#portfolio-flters li").removeClass('filter-active');
$(this).addClass('filter-active');
portfolioIsotope.isotope({ filter: $(this).data('filter') });
});
});
Here is my working demo video for review.
Your WP_Query is returning all products, so that is why they are all getting shown on page load. You need to change the query so it only gets the ones in the category/categories you want.
You want to get products in a certain category, e.g. food-products and all it's sub categories, (e.g. chocolates).
To do this, you can change your WP_Query to specify the category to use like this :
$loop = new WP_Query(
array('post_type' => 'product',
'posts_per_page' => -1,
array( 'category_name' => 'food-products' ) // <-- THIS!! Also note that it is in an array
));
This tells WP_Query to get all product posts that belong to the food-products category, so it will return any products with the food-products category as well as any products in any of the child categories, e.g. chocolates
WP_Query has a number of different ways you can query by category... take a look at the category section of the WP_Query documentation for more information.
UPDATE: Custom Taxonomies
You can do the same thing for custom taxonomies, but you need to use tax_query in the arguments instead of category_name. Your WP_Query should be something like this:
// you don't need to create a variable for the args, if just makes it clearer in the example
$args = array (
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array( // note the nested arrays
'taxonomy' => 'product_categories', // this is the name of your custom taxonomy
'field' => 'slug', // you can search by slug, name, term_id or term_taxonomy_id
'terms' => 'food-products' // the taxonomy slug to search for
)
)
);
$loop = new WP_Query($args);
You might need to change the values for taxonomy and term to match your custom taxonomy. I've also assumed you are searching by slug, but you can search by name or id either.
There is an include_children parameter for the tax_query that you use to say whether or not to include children (e.g. chocolates) in the results, but this defaults to true so you only need to use it if you don't want to include children.
Here's the taxonomy section of the WP_Query documentation for more information.
UPDATE 2: Getting the products for the current category
You say in the comments that you have one template for all of the terms taxonomy-product_categories.php, each category shows in its own page using this template but you only want to show the products with the current term.
What you need to do is use just the current term in the WP_Query, not all of them. You should be able to use get_queried_object() to get the current term and use it in your tax_query instead of hard coding the specific terms.
// get the term of the current page
// We can then use $currentterm->slug in tax_query to dynamically search for this term instead of hard coding a specific term
$currentterm = get_queried_object();
$args = array (
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array( // note the nested arrays
'taxonomy' => 'product_categories', // this is the name of your custom taxonomy
'field' => 'slug', // you can search by slug, name, term_id or term_taxonomy_id
'terms' => $currentterm->slug // search for the slug of the current term
)
)
);
$loop = new WP_Query($args);
So what this should do is: if you are on e.g. site.com/product-category/food-products, it will get the current term which is food-products and then only search for products with that category.
When you go to e.g. site.com/product-category/home-decor, it will dynamically pick up the new term as home-decor and use it in the query.

Let users sort posts in Wordpress

I’d like to create a page for filtering posts based on a number of criteria.
I can work with wp_query and deliver posts quite easily, my problem is that I can’t figure out (nor can I find any answers online about this, believe me I looked) how to let users do this.
Take this for example, returns the posts in order of price (custom field meta value) from highest to lowest with 33 posts.
<?php
$featuredPosts = new WP_Query( array(
'posts_per_page' => 33,
'meta_key'=>'Price',
'orderby' => 'meta_value_num',
'order' => DESC
) );
?>
<?php if ( $featuredPosts->have_posts() ) : ?>
<?php while ( $featuredPosts->have_posts() ) : $featuredPosts->the_post(); ?>
<article <?php post_class('item-post block'); ?> id="post-<?php the_ID(); ?>">
<h2 class="price-title"><?php the_title(); ?> </h2>
</article> <!-- end div post -->
<?php endwhile; wp_reset_query(); ?>
<?php endif; ?>
Now, even after reading and googling, I’ll be damned if I can figure out how I’d implement this on the front end for users to filter posts.
I mean, I know you can append to the URLs in Wordpress to alter the order of posts, but in this context I’m totally lost.
I tried this, but it doesn't work.
<?php
$by_price = esc_url(add_query_arg(array(
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => ASC
)));
$by_date = esc_url(add_query_arg(array(
'orderby' => 'date',
'order' => DESC
)));
?>
<ul>
<li>Order by price</li>
<li>Order by date</li>
</ul>
What I’m trying to achieve is actually quite simple as well, let the user choose the category, choose the price range (guessing I’d write something in JQuery to deliver a value into an field), set the number of results they’d like to be returned.
I’ve tried googling everything under the sun I can think of for this, no dice.
Try Simple Custom Post Order plugin.
It is using AJAX and JavaScript, you don’t have to load anything else. You have to just drag and drop the posts.
OK, I update the code to make it clear:
---I do not think meta_key would be auto-pickup---
functions.php
...
$whitList = array(
'price' => array(
'posts_per_page' => 33,
'meta_key'=>'price',
'orderby'=>'meta_value_num',
'order' => ASC
),
'date' => array(
'posts_per_page' => 33,
'orderby'=>'date',
'order' => DESC
)
);
...
Your first loop php:
<?php
gloabl $whitList; //to use the $whitList in your functions.php.
$aryQuery = $whitList[$_REQUEST['orderby']] ? $whitList[$_REQUEST['orderby']] : $whitList['price'];
$featuredPosts = new WP_Query( $aryQuery );
....
....
?>
For your list page:
<ul>
<?php
gloabl $whitList; //to use the $whitList in your functions.php.
foreach( $whitList as $orderby => $aryOrderBySettings){
?>
<li> Order by <?php echo $orderby;?></li>
<?php
}
?>
</ul>
Using $_GET parameters is the way to go here. First of all you'll want to allow your visitors access to these add these variables. The link approach is fine, overall, so we can generate augmented links by using the add_query_arg to tack on extra parameters to the current URL.
<?php
$urla = add_query_arg( 'sort' => 'price', 'asc' => '1' );
$urld = add_query_arg( 'sort' => 'price', 'asc' => '0' );
?>
Sort by price (asc)
Sort by price (desc)
When clicked, the tacked on variables can thus be detected:
<?php
// Get an allowed sort variable and the order
$sort = isset( $_GET['sort'] ) && in_array( $_GET['sort'], array( 'price' ) ) )
? $_GET['sort'] : null;
$order = isset( $_GET['asc'] ) && $_GET['asc'] == '0' ? 'DESC' : 'ASC';
?>
Now you would augment your main query with the data you just retrieved. If you're using the default way of querying posts on a page you should be able to get away with query_posts, although it is not recomended. And, if you're using a custom loop, simply inject the new arguments into it:
<?php
$args = array();
switch ( $sort ):
case 'price':
$args['order'] = $order;
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'price';
break;
default:
break;
endswitch;
$defaults = array( 'posts_per_page' => 33 );
$query = new WP_Query( wp_parse_args( $args, $defaults ) );
?>
You can add more variables, by creating more URLs and buttons to press, and more cases in the switch statement to extend the basic example above.
The first piece of code would go wherever you want your buttons to appear. The second piece of code goes before the third one, which goes before outputting the results.

I'm trying to make a list of all the posts classified under one term for a custom taxonomy.

I'm trying to make a list of all the posts classified under one term for a custom taxonomy.
I have created a custom post type called "testimonial" with a custom taxonomy of "testimonial categories". with in testimonial categories I have created the terms "colleagues" and "clients".
I am trying to create too archive pages. One that will list all of the posts under colleagues and the other list all posts under clients.
I have created the archive pages taxonomy-testimonial_categories-clients.php and taxonomy-testimonial_categories-colleagues.php. And can creat a list of all post under the cpt testimonials but can't filter it by the terms Colleagues or clients.
After research on wordpress.org I believe that using tax_query with new WP_Query is the way to go.
Here is the code I'm working with now.
<?php
$args = array(
'post_type' => 'testimonial',
'tax_query' => array(
array(
'taxonomy' => 'testimonial_categories',
'field' => 'slug',
'terms' => 'colleagues'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<span class="frame small alignleft">
<?php the_post_thumbnail(thumbnail); ?>
<span>
<div class="test-content">
<?php the_content(); ?>
</div>
<?php endwhile; ?>
Although its way too late here is the only solution that worked for me,
$my_taxonomy_name = "your taxo. name";
$my_term_name = "your term name";
$my_term_id = -1;
$terms = get_terms($my_taxonomy_name);
if(count($terms)>0){
foreach ($terms as $term) {
if($term->name == $my_term_name){
$term_id=$term->term_id;
continue;
}
}
$my_posts = array();
$postids_in_term = get_objects_in_term($term_id,'ad_setting');
foreach($postids_in_term as $post_id){
array_push($my_posts,get_post($post_id));
}
var_dump($my_posts);
}
In no way this is elegant, but hey, it works!

Wordpress - Custom taxonomy page of custom post type listing by terms

I have a taxonomy-taxonomy.php page that needs to look like so:
CUSTOM POST TYPE TITLE (RESOURCES)
Custom Taxonomy 1 (Resource Types)
Resource Type Term 1 (White Papers)
White Paper post 1
White Paper post 2
White Paper post 3
Resource Type Term 2 (Videos)
Videos post 1
Videos post 2
Videos post 3
Tried to make sense of all the new documentation for Wordpress 3.0, but it only made me more confused as it seems to be mixed up with 2.8.
It's not necessary to transform the object to an array, you can perfectly work with the object without too much hassle. What is curious (at least for me), is that you get something like this:
Array
(
[0] => stdClass Object
(
[term_id] => 7
[name] => Magister comunicaciones aplicadas
[slug] => magister-comunicaciones-aplicadas
[term_group] => 0
[term_taxonomy_id] => 7
[taxonomy] => linea-de-estudio
[description] =>
[parent] => 0
[count] => 4
)
[1] => stdClass Object
(
[term_id] => 8
[name] => Engagement marketing
[slug] => engagement-marketing
[term_group] => 0
[term_taxonomy_id] => 8
[taxonomy] => linea-de-estudio
[description] =>
[parent] => 0
[count] => 5
)
)
It's basically, an array of objects, so you've to treat them that way. For example if I want the name of the the first one:
$myterms = get_terms('taxonomy-name', 'orderby=none&hide_empty');
echo $myterms[0]->name;
If you need to iterate through the elements, you still can use foreach();.
foreach ($myterms as $term) { ?>
<li><?php echo $term->name; ?></li> <?php
} ?>
That way you can post the articles from your taxonomy.
For the custom post types, you'll have to create a loop like this:
$args = array(
'post_type' => 'post-type-name',
'taxonomy' => 'term'
//for example
//'resources' => 'videos'
);
// assigning variables to the loop
global $wp_query;
$wp_query = new WP_Query($args);
// starting loop
while ($wp_query->have_posts()) : $wp_query->the_post();
the_title();
blabla....
endwhile;
Then you can create multiple loops each of one for each taxonomy/term :).
If you want to get even more fancy (don't want to repeat yourself a hundred times) you can include the second loop inside the first one and assign variables to the taxonomy (resources ie) and the terms it has (videos) (from your example only the last one). The idea is that you would have a normal (typical) wordpress loop restricted to the custom post-type and each one of the terms.
foreach ($myterms as $term) : ?>
<li><?php echo $term->name; ?></li> <?php
$term_name = $term->slug;
$args = array(
'post_type' => 'post-type-name',
'taxonomy' => "$term_name"
);
// assigning variables to the loop
global $wp_query;
$wp_query = new WP_Query($args);
// starting loop posting only
while ($wp_query->have_posts()) : $wp_query->the_post();
the_title();
blabla....
endwhile;
endforeach; ?>
Obviously you can do the inverse thing too, create the normal loop for a single-template custom type (it's looks like you have only one), and inside includes all the custom terms.
Not very elegant, but that's the best way I can came up with it :P. Hope that someone can understand this, sounds confusing.
Maybe could it be possible with some callback function?.
Hey manon1165 , I actually just accomplished this. Was a huge pain, hopefully my code snippet will help!
I made a custom page template. And did something along the lines of
<?php $categories = get_terms('taxonomy-name', 'orderby=name&hide_empty=0'); $cats = object_to_array($categories); ?>
Now, just print_r($cats) and you will see the array of the categories.
You will need to convert the object to an array, I did so with.
function object_to_array($data)
{
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $data;
}
I did
<ul id="cat-list">
<?php foreach($cats as $cat) { ?>
<li><?php echo $cat['name']; ?> (<?php echo $cat['count']; ?>)<br><?php echo $cat['description']; ?></li>
<?php } ?>
</ul>
Hope that helps!
This worked fine for me:-
<?php
$custom_terms = get_terms('custom_taxonomy');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array('post_type' => 'custom_post_type',
'tax_query' => array(
array(
'taxonomy' => 'custom_taxonomy',
'field' => 'slug',
'terms' => $custom_term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h2>'.$custom_term->name.'</h2>';
while($loop->have_posts()) : $loop->the_post();
echo ''.get_the_title().'<br>';
endwhile;
}
}
>?

Resources