Wordpress WP_Term_Query Custom Taxonomy Select Options - php

The below code works really well for pulling in a select option list for all the entries in a custom taxonomy called 'make'. It only pulls in parent level ones which is perfect.
<select id="make" name="make">
<option value="">--</option>
<?php $term_query = new WP_Term_Query( array( 'taxonomy' => 'make', 'parent' => 0 ) ); if ( ! empty( $term_query->terms ) ) {
foreach ( $term_query ->terms as $term ) {
echo '<option class="' . $term->name . '" value="' . $term->name . '">' . $term->name . '</option>';
}
} else {
};?>
</select>
However, i would like to create another identical version of this code but instead of pulling in a list of all the parent values, it should pull in all the child values. Not for a particular page or post, but should output a select list of ALL the child entries of a custom taxonomy, ignoring the parents. Any help is massively appreciated!

you could use get_term_children and get_term_by functions to build your second select:
<select id="make" name="make">
<option value="">--</option>
<?php
$term_query = new WP_Term_Query( array( 'taxonomy' => 'make', 'parent' => 0 ) );
if ( ! empty( $term_query->terms ) ) {
foreach ( $term_query ->terms as $term ) {
$term_children = get_term_children( $term->term_id, 'make' );
foreach($term_children as $children){
$child = get_term_by( 'id', $children, 'make' );
echo '<option class="' . $child->name . '" value="' . $child->name . '">' . $child->name . '</option>';
}
}
} else {
};
?>
</select>

Related

Drop-down filter is not working as it should

My code:
<?php
function filter_profiles_by_country()
{
$url = get_site_url();
if ( $terms = get_terms( array('taxonomy' => 'country','orderby' => 'name') ) )
{
// if categories exist, display the dropdown
echo '<select name="categoryfilter" onchange="if (this.value) window.location.href=this.value">';
echo ' <option value="'.$url.'/profiles">All Profiles...</option>';
foreach ( $terms as $term )
{
// ID of the category as an option value
echo ' <option value="'.$url ."/country/". $term->name . '">' . $term->name . '</option>';
}
echo '</select>';
}
}
?>
When I click on All Profiles, it should take me to /profiles/ page. But it is not working.
<?php
function filter_profiles_by_country(){
$url = get_site_url();
global $wp;
$current_url = home_url(add_query_arg(array(), $wp->request));
if( $terms = get_terms( array(
'taxonomy' => 'country',
'orderby' => 'name'
) ) ) :
// if categories exist, display the dropdown
echo '<select name="categoryfilter" onchange="if (this.value) window.location.href=this.value"><option value="'.$url.'/profiles/">All Profiles...</option>';
foreach ( $terms as $term ) :
$loadedItem = $url."/country/".$term->name;
$selectedItem = ($current_url == $loadedItem)? "selected": "";
echo '<option '.$selectedItem.' value="'.$url ."/country/". $term->name . '">' . $term->name . '</option>'; // ID of the category as an option value
endforeach;
echo '</select>';
endif;
}
?>
Try this.

If parent category is checked, don't echo children category

I have this Continent -> Country category setup for a custom post type.
- Africa (parent 1)
- Uganda
- Zambia
- Zimbabwe
- Asia (parent 2)
- Afghanistan
- Bahrain
- Bangladesh
- Bhutan
If parent category is checked for a post, don't echo the children categories. (even if one or more children is checked) echo => Africa, Asia
And the revert, if one or more child categories is checked, but the parent category is NOT checked. Show only the child categories. echo => Uganda, Zambia, Zimbabwe, Afghanistan, Bahrain, Bangladesh, Bhutan
UPDATE
Also if Africa (parent 1) is checked, while Asia (parent 2) is NOT checke, but Afghanistan and Bhutan (children of parent 2) is checked the output should be: echo => Africa, Afghanistan, Bhutan.
This will only output IF there is one or more parent categories checked.
<?php
$post = get_post(); // If $post is already available, skip.
$terms = get_the_terms( $post->ID, 'custom-category' );
foreach ( $terms as $term ) :
if ( $term->parent === 0 ) :
echo '<a href="' . esc_url( get_term_link( $term->term_id, 'custom-category' ) ) .
'" title="' . esc_html( $term->name ) . '" ' . '>' . esc_html( $term->name ) .
'</a> ';
endif;
endforeach;
?>
How to output the child catergories if their parent is NOT checked?
Please try below code which help you for logic of the need you may modify it for your output requirements
$post = get_post(); // If $post is already available, skip.
$terms = get_the_terms( $post->ID, 'category' );
$outputparent = $outputchild = array();
foreach( $terms as $term ) :
if( $term->parent === 0 ) :
$outputparent[] = '<a href="' . esc_url( get_term_link( $term ) ) .
'" title="' . esc_html( $term->name ) . '" ' . '>' . esc_html( $term->name ) .
'</a> ';
else :
$outputchild[] = '<a href="' . esc_url( get_term_link( $term ) ) .
'" title="' . esc_html( $term->name ) . '" ' . '>' . esc_html( $term->name ) .
'</a>';
endif; //Endif
endforeach;
if( !empty( $outputparent ) ) :
echo 'Parent category is checked<br>';
echo implode('<br>', $outputparent);
$outputchild = array();
elseif( !empty( $outputchild ) && empty( $outputparent ) ) :
echo 'Only Childs<br>';
echo implode('<br>', $outputchild);
endif;
I manage to figure out a solution to this problem! This is tested and produces my desired result! If you have a more elegant solution, please let me know!
<?php
$categories = get_the_terms( $post->ID, 'custom-category' );
// If term is a parent, add to post_parent array.
$post_parent = array();
foreach( $categories as $parent_id ) {
if($parent_id->parent < 1) {
$post_parent[] = $parent_id->term_id;
}
}
// If terms parentId does not exist in post_parent array
// add to array regions as a key => value pair
$regions = array();
foreach( $categories as $category ) {
if (!in_array($category->parent, $post_parent)) {
$regions[$category->term_id] = $category->name;
}
}
// Sort terms based on keys (regions), impolde and print
ksort($regions);
$locations = array();
foreach($regions as $key => $value) {
$locations[] = ' ' . $value . '';
}
echo implode(",", $locations);
?>

Product category filter displaying a list of products with their stock in Woocommerce

Im trying to create a stock report for my store which is mainly for "variable" and some "simple" products.
The idea is the user selects the category from a drop-down list and page refreshes showing the stock for the chosen category.
The problem im having seems to be with the form sending the data to the query.
If I manually code the slug for the category I want everything works fine for variable and simple products. however, when I try to implement the form to Post the category to the query I start getting debug errors below.
[20-Sep-2018 09:52:42 UTC] PHP Fatal error: Uncaught Error: Call to undefined method WC_Product_Simple::get_available_variations() in C:\wamp64\www\devbb.co.uk\wp-content\themes\bb-theme\page-stock.php:79
Stack trace:
#0 C:\wamp64\www\devbb.co.uk\wp-includes\template-loader.php(74): include()
#1 C:\wamp64\www\devbb.co.uk\wp-blog-header.php(19): require_once('C:\\wamp64\\www\\d...')
#2 C:\wamp64\www\devbb.co.uk\index.php(17): require('C:\\wamp64\\www\\d...')
#3 {main}
thrown in C:\wamp64\www\devbb.co.uk\wp-content\themes\bb-theme\page-stock.php on line 79
The part I really don't understand is the fact that when i write the category in myself everything works but when the form tries to pass the same data all the errors appear?
Any help would be really appreciated, thanks
My Code:
<main>
<form id="test" name="test1" method="post">
<select id="cat-select-box" name="amt_per">
<?php
$cat_args = array(
'taxonomy' => "product_cat",
'orderby' => 'slug',
'order' => 'ASC',
'hide_empty' => 1,
);
$cats_select_list = get_terms( 'product_cat', $cat_args );
foreach ($cats_select_list as $select_list){
//if ( strpos($select_list->slug, 'express') || ( strpos($select_list->slug, 'clearance') ) === false) {
echo '<option class="amt-button" name="amt_per" value="' . $select_list->slug . '">' . str_replace ('-', ' ', $select_list->slug) . '</option>';
//}
}
?>
</select>
</form>
<table id="fx_stock_manager">
<?php
$default = 'my-hockey-club-clearance';
$club_cat = isset($_POST['amt_per'])? $_POST['amt_per']: $default;
$query = new WC_Product_Query( array(
//'limit' => 10,
'orderby' => 'title',
'order' => 'ASC',
'return' => 'ids',
//'category' => 'my-hockey-club-clearance',
'category' => $club_cat,
) );
$products = $query->get_products();
foreach ($products as $prod) {
$actual = wc_get_product( $prod );
$variations = $actual->get_available_variations();
foreach ($variations as $key => $value) {
echo '<tr>';
echo '<td><a title="' . $actual->get_sku() . '" href="' . get_permalink($actual->get_id()) . '">' . $actual->get_name() . '</a></td>';
echo '<td>';
foreach ($value['attributes'] as $attr_key => $attr_value) {
$prefix = 'attribute_pa_';
$str = $attr_key;
if (substr($str, 0, strlen($prefix)) === $prefix) {
$str = substr($str, strlen($prefix));
}
echo '<table>';
echo '<tr>';
echo '<td>' . $str . '</td>';
echo '<td>' . $attr_value . '</td>';
echo '</tr>';
echo '</table>';
}
echo '</td>';
echo '<td class="fx_stock_count">' . $value['availability_html'] . '</td>';
echo '</tr>';
}
}
?>
</table>
<script>
$(function() {
$('#cat-select-box').on('change', function(e) {
$(this).closest('form')
.trigger('submit')
})
})
</script>
There are some mistakes in your code since Woocommerce 3… I have also made some little additions:
- to keep the selected menu item when item on reload,
- added a labeled starting option.
Try the following instead:
<main>
<form id="test" name="test1" method="post">
<select id="cat-select-box" name="amt_per">
<option class="amt-button" value=""'.$selected.'><?php _e("Chose a category"); ?></option>
<?php
$product_categories = get_terms( array(
'taxonomy' => "product_cat",
'orderby' => 'slug',
'order' => 'ASC',
'hide_empty' => 1,
));
foreach ($product_categories as $term ){
$selected = isset($_POST['amt_per']) && $_POST['amt_per'] == $term->slug ? ' selected' : '';
echo '<option class="amt-button" value="' . $term->slug . '"'.$selected.'>' . $term->name . '</option>';
}
?>
</select>
</form>
<table id="fx_stock_manager">
<?php
$club_cat = isset($_POST['amt_per'])? $_POST['amt_per']: 'my-hockey-club-clearance';
$products = wc_get_products( array(
//'limit' => 10,
'orderby' => 'title',
'order' => 'ASC',
'category' => $club_cat,
) );
foreach ($products as $product) {
if( $product->is_type('variable')){
foreach ($product->get_available_variations() as $values ) {
echo '<tr><td><a title="' . $values['sku'] . '" href="' . get_permalink($values['variation_id']) . '">' . get_the_title($values['variation_id']) . '</a></td>
<td>';
foreach ($values['attributes'] as $attribute => $term_slug) {
$taxonomy = str_replace('attribute_', '', $attribute);
$attr_name = get_taxonomy( $taxonomy )->labels->singular_name; // Attribute name
$term_name = get_term_by( 'slug', $term_slug, $taxonomy )->name; // Term name
echo '<table>
<tr>
<td>' . $attr_name . '</td>
<td>' . $term_name . '</td>
</tr>
</table>';
}
echo '</td>
<td class="fx_stock_count">' . $values['availability_html'] . '</td>
</tr>';
}
}
}
?>
</table>
<script>
jQuery(function($) {
$('#cat-select-box').on('change', function() {
if( $(this).val() != '0' )
$(this).closest('form').trigger('submit')
})
})
</script>
Tested and works.

i want to get the current category term in the select box in word press

this is my taxonamy code in word press
<?php
$terms = get_terms(['taxonomy' => 'listing_type', 'hide_empty' => false,]);
if ($terms) {
foreach ($terms as $term) {
$selected = 'selected';
echo '<option value="' . $term->name . '" '.$selected.' >' .esc_attr($term->name) . '</option>';
}
} ?>
Instead of writing this manually you can just use wp_dropdown_categories()
Docs here — https://codex.wordpress.org/Function_Reference/wp_dropdown_categories
Thanks,
Tom

Get selected value from dropdown menu, from an array?

I feel like I am really missing something here. I did some manual customizations on a short (wordpress) script and try to set a <select><option> to "selected" if it has been selected. In order to accomplish this, I tried to find out if the $term->id = similar to the selected option value (which is an ID as well). All good so far, but I cannot seem to get the submitted <select><option>. All it says is 'array'.
Below is my script. Does anyone see what I am doing wrong here? To be clear, it seems to be all about the $_GET["listing_cat"] here. Also when i try to print the $_GET["listing_cat"] within the foreach all it outputs is 'array'.
<form method="get" action="<?php echo trailingslashit( home_url() ); ?>" class="custsearch">
<select name="listing_cat[]">
<option value="1" disabled="disabled" <?php if(!count($_GET)>0 || !$_GET["listing_cat"] ){ echo 'selected="selected"';} ?>>Pls choose</option>
<?php
$cat_args = array(
'orderby' => 'id',
'parent' => 0,
'hide_empty' => false
);
$terms = get_terms('listing_category', $cat_args );
foreach ($terms as $term) {
printf( '<option class="level-0" value="' . $term->term_id .'"');
if($_GET["listing_cat"] == $term->term_id) { echo 'selected="selected"'; }
printf( '>%s</option>', $term->slug, $term->name );
}
?>
</select>
</form>
Ok here is all that i needed.. quite logical;). I put it into a function and needed the in_array() to check:
//category in dropdown
function the_refine_category_ui2() {
$cat_args = array(
'orderby' => 'id',
'parent' => 0,
'hide_empty' => false
);
$terms = get_terms('listing_category', $cat_args );
foreach ($terms as $term) {
printf( '<option class="level-0"');
if( in_array( $term->term_id, $_GET["listing_cat"] )) { echo 'selected ';}
printf('value="' . $term->term_id .'"');
printf( '>%s' . $term->term_id .'</option>', $term->slug, $term->name );
}
}

Categories