I am trying to get all the Product Categories inside a Wordpress Plugin with the following Code. I have tried the same code within the active theme and they are working and gives the right output but when I am trying to do the same inside the plugin file it returns an empty array. Is there any other way to do this? wht get_categories()
is not working inside the plugin file?
EDIT: this I am using as the response to a AJAX call as below.
My Code as follow,
add_action( 'wp_ajax_tcf_et_mp_get_categories', 'tcf_et_mp_get_categories' );
function tcf_et_mp_get_categories(){
$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 = 1;
$args = array( 'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty );
$all_materials = get_categories( $args );
foreach($all_materials as $material){
$materials_drop_down .= '<option value="'.$material->term_id.'" '.$selected_str.'>'.$material->name.'</option>';
}
//print_r( $all_materials );
wp_send_json( $materials_drop_down );
die();
}
Finally I could solve this with MySQL Query here I m trying to get Woocommerce Product Categories in a WP AJAX function where get_categories()
or get_terms()
does not work for product_cat
taxonomy. But within this function I can execute WP MySQL Quires so the following code produces and returns the expected output.
add_action( 'wp_ajax_tcf_et_mp_get_categories', 'tcf_et_mp_get_categories' );
function tcf_et_mp_get_categories()
{
global $wpdb;
$categories = $wpdb->get_results( " SELECT wp_terms.*
FROM wp_terms
LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
WHERE wp_term_taxonomy.taxonomy = 'product_cat'" );
$materials_drop_down = '<select>';
$materials_drop_down .= '<option value="0">Choose Material Type</option>';
foreach( $categories as $category )
{
$materials_drop_down .= '<option value="'. $category->term_id .'">' . $category->name . '</option>';
}
$materials_drop_down = '</select>';
wp_send_json( $materials_drop_down );
die;
}
Hope this will help for someone.