Been banging my head for a few hours trying to sort this. Finally got a function together that will list all the terms in a custom taxonomy I created in Woocommerce > Products, which works.
What I want to do:
Get/Display the image for each term next to the title (Created an Image field with ACF for that taxonomy item) and display the description underneath.
I can probs figure out the description part, but having a hard time with getting the image to render.
Here's what I've got so far:
//---------Start ACF code
//
// Define taxonomy prefix
// Replace NULL with the name of the taxonomy eg 'category'
$taxonomy_prefix = 'item';
// Define term ID
// Replace NULL with ID of term to be queried eg '123'
$term_id = NULL;
// Define prefixed term ID
$term_id_prefixed = $taxonomy_prefix .'_'. $term_id;
//----------End ACF Code
$taxonomy = 'item';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
$image = get_field('image', $taxonomy . '_' . $term_id);
echo ' <img src="'.the_field( 'image', $term_id ) .'" /> ';
echo ''. $cat->name .'<br />';
$args2 = array(
'taxonomy' => $taxonomy,
'child_of' => 0,
'parent' => $category_id,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<a class="subcat" href="'. get_term_link($sub_category->slug, 'item') .'">'. $sub_category->name .'</a><br/>';
}
}
}
}
You can see the output here:
https://doorsdev.wpengine.com/individual-flower-essence-descriptions/
When I inspect I can see the field rendering but a blank src attribute, and with no errors on the page, I'm not sure what to do next.
I'm guessing it's something to do with the $term_id, becuase it tells me to define it, but since I don't want one specific term, I want it for each term that gets pulled into the loop....I'm not sure how to define that.
Any help appreciated.
Thanks!
as shown in the code your $term_id is null. Try replacing $term_id with $category_id.
Replace this code(EDITED).
$image = get_field('image', 'term_' . $category_id);
echo ' <img src="'.$image .'" /> ';
Reference: https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/
Related
I want to create a drop down list for categories in php in a page built in code. I could create a shortcode for it successfully but since shortcode is not friendly with html, I decided not to pursue that route. So without any scripts or jquery, I'm attempting to add php code into a div
<select class="store-search-input form-control" name="dokan_seller_search" value="<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
echo '<br />'. $cat->name .'';
$args2 = array(
'taxonomy' => $taxonomy,
'child_of' => 0,
'parent' => $category_id,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
}
}
}
?>" >
</select>
and this happened:
Any help would be appreciated
Update thanks to Alex's help:
I don't have enough points to add the image directly yet:
<input type="select" class="store-search-input form-control" name="dokan_seller_search" value="<?php
$args = array(
'taxonomy' => 'product_cat',
'orderby' => 'name',
'hierarchical' => true,
'hide_empty' => false
);
$all_categories = get_categories( $args );
esc_html('<select class="store-search-input form-control" name="dokan_seller_search">');
foreach($all_categories as $parent){
if ($parent->category_parent == 0) {
echo '<option value="'.$parent->name.'"><a href="'. get_term_link($parent->slug, 'product_cat') .'">'. $parent->name .'</option>';
}
$args2 = array(
'taxonomy' => 'product_cat',
'child_of' => $parent->term_id,
'parent' => $parent->term_id,
'hide_empty' => 'false'
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name;
}
}
}
esc_html('</select>');
?>">
The result I'm expecting is a
What you are trying to do is a little dirty for a . You would be much better off using a dropdown triggered by javascript so you can better control the DOM in the dropdown. A select should really only be used when you need to submit data to the server.
UPDATE: This is tested and working.
<script type="text/javascript">
//First, some js to trigger the window to relocate when you click an option
jQuery(document).ready(function(){
//When the select is triggered
jQuery('#category-links').on('click', function(){
//Get the URL from the selected option
var url = jQuery(this).val();
//Navigate to the url
window.location.replace(url);
})
})
</script>
<?php
//Get the parent terms
$parents = get_terms([
'taxonomy' => 'product_cat',
'hide_empty' => false,
'parent' => 0
]);
//Start the dom for the select
echo '<select id="category-links">';
echo '<optgroup>';
//The parent option
echo '<option value="'.get_term_link($term->term_id).'">'. $term->name .'</option>';
//Check for children, if there are we'll add them here
$children = get_term_children($term->term_id, 'product_cat');
if (!empty($children)) {
foreach ($children as $child) {
$childterm = get_term_by('id', $child, 'product_cat');
echo '<option value="'.get_term_link($childterm->term_id).'">'. $childterm->name .'</option>';
}
}
echo '</optgroup>';
}
echo '<select>';
after a lot of research i came across this: https://rudrastyh.com/wordpress/ajax-post-filters.html
But I can only get it to work when there are two options selected.
I'll give you some context:
I have a CPT named 'Contratistas' that has two custom taxonomies 'especialidad' and 'industria', they both have two terms each 'especialidad' -> 'tecnologia' and 'auditoria'; 'industria' -> 'cultivo' and 'depocito'
here is my function:
function misha_filter_function(){
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_per_page' => -1,
'post_type' => 'contratista'
);
// for taxonomies / categories
if( isset( $_POST['filtroEspecialidad'] ) && isset ($_POST['filtroIndustria']) ) {
$args['tax_query'][] = array(
//'relation' => 'AND',
array(
'taxonomy' => 'especialidad',
'field' => 'id',
'terms' => $_POST['filtroEspecialidad']
),
array(
'taxonomy' => 'industria',
'field' => 'id',
'terms' => $_POST['filtroIndustria']
),
);
} elseif( !isset($_POST['filtroEspecialidad'] ) && isset($_POST['filtroIndustria']) ) {
$args['tax_query'][] = array(
'taxonomy' => 'industria',
'field' => 'id',
'terms' => $_POST['filtroIndustria']
);
} elseif( isset( $_POST['filtroEspecialidad'] ) && !isset($_POST['filtroIndustria']) ) {
$args['tax_query'][] = array(
'taxonomy' => 'especialidad',
'field' => 'id',
'terms' => $_POST['filtroEspecialidad']
);
}
It works if you select something from both taxonomies, but when one is empty it says 'there are no post'
as a bonus I will like to show all the post before filtering.
I hope somebody can help me! Thanks! I'm fairly new to Wordpress
EDIT! Here is my js and my form, i'm at a loss here I can't figure out what's wrong :(
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('.filtrar').text('Procesando...'); // changing the button label
},
success:function(data){
filter.find('.filtrar').text('Filtrar'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
my php file:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<div class="titulo mb-3">
<h3>Especialidad</h3>
</div>
<?php
if( $terms = get_terms( array( 'taxonomy' => 'especialidad', 'orderby' => 'name' ) ) ) :
echo '<select name="filtroEspecialidad"><option value="">Seleccione una especialidad...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<div class="titulo my-3">
<h3>Industrias</h3>
</div>
<?php
if( $terms = get_terms( array( 'taxonomy' => 'industria', 'orderby' => 'name' ) ) ) :
echo '<select name="filtroIndustria"><option value="">Seleccione una industria...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<button class="my-3 filtrar">Filtrar</button>
Clear
<input type="hidden" name="action" value="myfilter">
</form>
You may want to give the Taxonomy Parameters of WP_Query() another glance. Unfortunately, WordPress is a little loose with it's id parameter names contextually. I'm not entirely sure your initial "both" is working like you intend either, because 'field' => 'id' is actually invalid.
From the docs:
field (string) – Select taxonomy term by. Possible values are term_id, name, slug or term_taxonomy_id. Default value is term_id.
id isn't actually a valid option. If you're just using the term_id, you should be able to omit that. You can also just programatically add the tax_query array arguments based on if that filter is set, instead of checking for "both set, this set/that unset, this unset, that set", something like this perhaps?
function misha_filter_function(){
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_per_page' => -1,
'post_type' => 'contratista'
);
if( isset($_POST['filtroEspecialidad']) || isset($_POST['filtroIndustria']) ){
$args['tax_query'] = array();
if( isset($_POST['filtroEspecialidad']) ){
$args['tax_query'][] = array(
'taxonomy' => 'especialidad',
'terms' => $_POST['filtroEspecialidad']
);
}
if( isset($_POST['filtroIndustria']) ){
$args['tax_query'][] = array(
'taxonomy' => 'industria',
'terms' => $_POST['filtroIndustria']
);
}
if( count($args['tax_query']) > 1 ){
$args['tax_query']['relation'] = 'AND';
}
}
// Run WP_Query with new $args, etc.
}
I'm not sure if the $_POST values are arrays or single numbers, but you may want to validate those with array_map and/or absint if you're using user-supplied input, but if they're just IDs, the above should work for now.
I was trying to create shortcode for custom taxonomy terms dynamically. But failing to do so.
Suppose, if there is a term called "wordpress" then I should be able to query all the posts associated with that term via shortcode.
To be more precise, suppose if there is a taxonomy called 'event' and under that taxonomy there are multiple terms. So, I was trying to query posts under each of the term via shortcode of each of the term.
Here is what I tried:
function wordpress_recent_post( $atts, $content ) {
$a = shortcode_atts( array(
'cat' => '',
), $atts );
$args = array(
'posts_per_page' => 1,
'offset' => 0,
'category_name' => $a['cat'],
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'ignore_sticky_posts' => true,
);
$recent_posts = new WP_Query( $args );
ob_start();
if ( ! $recent_posts-> have_posts() ) {
return 'No Posts Found for ' . $a['cat'];
}
while ( $recent_posts->have_posts() ) {
$recent_posts->the_post();
the_title( '<h2>', '</h2>' );
if ( '' != $a['cat'] ) {
$href = '/category/' . $a['cat'];
} else {
$href = '/blog';
}
echo "<p><a href='$href'>Read More" . ucwords( $a['cat'] ) . '</a></p>';
}
wp_reset_query();
return ob_get_clean();
}
add_shortcode( 'wordpress_recent_post', array($this, 'wordpress_recent_post') );
And then I used this to call the posts from a term called "features" whose id is '183' (suppose)
[wordpress_recent_post cat="183"]
Any help would be really very appreciable.
Thanks!
Adding term slug did it. There should be slug not id, like this:
[wordpress_recent_post cat="features"]
I'm having a really hard time with this... essentially I just want to display breadcrumbs on the product category pages in woocommerce so that it shows the main category and sub categories. Hoping some smart kind soul can help me :)
This normally could be done easily with the following code:
<?php woocommerce_breadcrumb(); ?>
However, I'm using a purchased theme with woocommerce integrated, so it doesn't have that function and I tried to integrate it but no luck.
So, I found someone who had the same issue and made my own breadcrumbs for prordu. Which works, but I just want the product category to show ONLY the main category and sub category each product have. The code shows ALL categories and sub categories, not just the one I want to display.
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
?>
<?php $all_categories = get_categories( $args );
//print_r($all_categories);
foreach ($all_categories as $cat) {
//print_r($cat);
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
?>
<?php
echo '<br />'. $cat->name .''; ?>
<?php
$args2 = array(
'taxonomy' => $taxonomy,
'child_of' => 0,
'parent' => $category_id,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
} ?>
<?php }
}
?>
Is there any easy way to list all taxonomies for custom post type with permalinks?
taxonomy=title&post_type=company
The following does not seams to work, it is listing the categories for posts only:
$args = array (
'type' => 'company', //your custom post type
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0 //shows empty categories
);
$categories = get_categories( $args );
foreach ($categories as $category) {
echo $category->name;
$post_by_cat = get_posts(array('cat' => $category->term_id));
echo '<ul>';
foreach( $post_by_cat as $post ) {
setup_postdata($post);
echo '<li>'.the_title().'</li>';
}
echo '</ul>';
}
try changing
'type' => 'company', //your custom post type
to
'post_type' => 'company', //your custom post type
Change
'type' => 'company', // your custom post type
to
'taxonomy' => 'yourtaxonomyname', // your custom taxonomy
see also http://codex.wordpress.org/Function_Reference/get_categories
This should work:
$index_query = new WP_Query(array('post_type' => 'company', 'posts_per_page' => '-1', 'order' => 'DESC'));
while ($index_query->have_posts()) : $index_query->the_post();
$taxonomy_ar = get_the_terms($post->ID, 'tax-name');
$output = '<span class="btn">';
foreach($taxonomy_ar as $taxonomy_term) {
$output .= ''.$taxonomy_term->name.' <span class="label">'.$taxonomy_term->count.'</span> ';
}
$output .= '</span>';
echo $output;
endwhile;