How to attach custom taxonomy to a post in Wordpress? - wordpress

A have a lot of posts with custom post types in the database. In the same time the theme created the taxonomy institution:
function my_taxonomies_institutions() {
$labels = array(
'name' => _x( 'Category', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
// and tothers
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'show_admin_column' => true,
'rewrite' => array( 'hierarchical' => true, 'slug' => 'institutions' ),
);
register_taxonomy( 'institutions', 'institution', $args );
}
add_action( 'init', 'my_taxonomies_institutions', 0 );
OK, there's a menu item Instituitions in admin zone, and a bit of Categories there, for example - Sections. Now in order to animate the theme that constructed for this taxonomy I need to go through all posts and to attach the Instituitions term to the post depending of it's post_type.
print term_exists('sections'); // 7
I tried the following
$ret = wp_set_post_terms($pid, 7, 'institution');
$ret = wp_set_post_terms($pid, 'sections', 'institution');
but result was
WP_Error Object ( [errors] => Array ( [invalid_taxonomy] => Array ( [0] => Неверная таксономия. ) ) [error_data] => Array ( ) )
What I'm doing wrong?

You registered taxonomy with name institutions but using institution by mistake, hence te error [invalid_taxonomy]. It should be like this
$ret = wp_set_post_terms($pid, array(7,), 'institutions');
$ret = wp_set_post_terms($pid, array('sections',), 'institutions');
To assign this term "sections" with term_id = 7 to all posts of type institution, do something like
$posts = get_posts(array(
'post_type' => 'institution',
'post_status' => 'publish',
'posts_per_page' => -1
));
foreach ( $posts as $post ) {
wp_set_post_terms( $post->ID, array(7,), 'institutions');
// OR
// wp_set_post_terms( $post->ID, array ('sections',), 'institutions');
}
I hope this will work.
Please have a look at this codex page for further info.

try something like:
$posts = get_posts([
'post_type' => 'institution',
'post_status' => 'publish',
'numberposts' => -1
]);
foreach ( $posts as $post ) {
wp_set_post_terms( $post->ID; array( ), 'institutions');
}
also if you want to wp_set_post_terms by id, you should use wp_set_post_terms( $post->ID; array( $id )) instead of wp_set_post_terms( $post->ID; $id) take a look here

Related

Cannot fetch posts with certain "product_cat". WP_Query is empty

I want to set attributes for woocommerce products in certain product category. The query, however, doesn't seem to work.
I've placed the following code into functions.php of my child-theme.
Tried replacing slug by term_id, tried adding 'relation', just in case, tried to set the slug explicitly instead of variable, but still no luck.
UPD: wc_get_products and WC_Product_Query don't work either.
function wccategory_set_attributes($categoryslug, $attributes) {
$pquery = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 10,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $categoryslug,
),
),
));
if( $pquery->have_posts() ) {
while ($pquery->have_posts()) : $pquery->the_post();
foreach ($attributes as $name => $value) {
wp_set_object_terms( $postid, $value, $name, false );
$product_attributes[$i] = array (
'name' => htmlspecialchars( stripslashes( $name ) ),
'value' => $value,
'is_visible' => 1,
'is_taxonomy' => 0
);
$i++;
}
update_post_meta( $postid,'_product_attributes', $product_attributes);
endwhile;
}
}
wccategory_set_attributes('theslug', array ( 'pa_length' => '', 'pa_width' => '', 'pa_type' => ''));
$pquery->have_posts() returns nothing. The posts are present, though. Once I remove 'tax_query' from arguments, all works. I assume, that there is some error in 'tax_query'. I looked many other examples, it looks fine, but it seems I'm missing something.
Have you tried using get_posts() instead? If you're simply trying to retrieve a post count the full query may not be necessary, and get_posts returns an array on its own.
Also, rather than trying to work with the returned items outside the function, if the only thing you are returning is the post count, just returning the count? Lastly, post_count is different from found_posts. If you have a posts per page set, your post_count will always max out at that number, found_posts will provide all posts that were found in that query.
function get_cat_products_by_slug($category) {
$products = get_posts(
array(
'posts_per_page' => -1,
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category->slug,
)
)
)
);
$number_of_posts = $products->found_posts;
return $number_of_posts;
};
$p_query = get_cat_products_by_slug($category);
echo $p_query;

WordPress include custom field in search

I have a custom post type of post_type_1 in WordPress, I also have a custom field in that post type of custom_field_data
I am doing a search for apples by querying posts using wp_query like this...
$search_term = 'apples';
$args = array(
'post_type' => array('post_type_1'),
'post_status' => array('publish'),
'posts_per_page' => -1,
's' => sanitize_text_field( $search_term)
);
$results= new WP_Query( $args );
This works correctly and returns all posts with apples in the title, but I would also like to extend the search to the custom field custom_field_data so the query will return all posts with apples in either title or custom field.
What is my best approach? I have tried using a meta_query but haven't been successful. Does anybody have an example?
Use below code will work for custom field search.
$custom_field = $_GET['custom_field '] != '' ? $_GET['custom_field '] : '';
$search_term = 'apples';
$args = array(
'post_type' => array('post_type_1'),
'post_status' => array('publish'),
'posts_per_page' => -1,
's' => sanitize_text_field( $search_term),
'meta_query' => array(
array(
'key' => 'custom_field_key',
'value' => $custom_field ,
'compare' => 'LIKE',
),
)
);
$results= new WP_Query( $args );
Tested and works well.

WordPress WooCommerce API: Update/insert custom taxonomy terms

I am trying to update a products custom taxonomy term via the wp-json api.
I have added the below function to handle taxonomies:
function wp_api_add_tax($post, $data, $update){
foreach( $data['custom_tax'] as $tax => $val ){
wp_set_post_terms( $post['ID'], $val, $tax );
}
}
add_filter('json_insert_post', 'wp_api_add_tax', 10, 3);
And then add then taxonomy term like this:
$api_response = wp_remote_post( 'https://example.com/wp-json/wc/v2/products/4286', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'xxxxxxxxxxxx:xxxxxxxxxx' )
),
'body' => array(
'stock_quantity' => '0',
'categories' => array(
array(
'id' => 373
),
array(
'name' => 'Build Lean Muscle'
)
),
'custom_tax' => array(
'My Taxonomy Here' => 'My Term Here'
),
'meta_data' => array(
array(
'key' => 'nutritional',
'value' => 'nutritional description by the api 2'
)
)
)
) );
Is this the correct way of doing things? The custom taxonomy term does not get updated.

How to set taxonomy in custom plugin?

I am trying to create a plugin, I need a custom post and taxonomy. But it can be accessible in admin side, but the taxonomy is not working on front-end.
This is how I registered the custom post and taxonomy:
function post_type_questionnaire()
{
$labels = array(
'name' => _x('Questionnaire', 'post type general name'),
'singular_name' => _x('Questionnaire', 'post type singular name'),
'add_new' => _x('Add New Question', 'questionnaire'),
'add_new_item' => __('Add New Questionnaire')
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'_builtin' => false, // It's a custom post type, not built in!
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title',
//'editor',
/*'excerpt',
'thumbnail',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'author',
'page-attributes'*/
));
register_post_type('questionnaire',$args);
}
add_action('init', 'post_type_questionnaire');
function create_questionnaire_taxanomies(){
register_taxonomy('qcategories','questionnaire', array(
'hierarchical'=>true,
'label'=>'Questionnaire Categories',
'rewrite' => array( 'slug' => 'questionnaire' )
));
}
add_action('init', 'create_questionnaire_taxanomies',0);
I am using a shortcode to display it in front-end.
by using the code below it shows all posts
$args = array(
'post_type' => 'questionnaire',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
if ( $query->have_posts() ) { ?>
<?php while ( $query->have_posts() ) :query->the_post(); ?>
But when I try to specify a taxonomy term it doesn't work and this is the code:
$args = array(
'post_type' => 'questionnaire',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'qcategories',
'field' => 'slug',
'terms' => $atts["name"]
)
)
);
$query = new WP_Query($args);
if ( $query->have_posts() ) { ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
When I tried to display the count of post in a template page it show nothing:
$term = get_term( 3, 'qcategories' );
echo $term->count;
This outputs nothing, so I believe that the taxonomy is not registering, can anybody help me to register the taxonomy in my custom plugin. Thanks in advance!
Edited
This is the output of $args:
array (size=3)
'post_type' => string 'questionnaire' (length=13)
'posts_per_page' => int -1
'tax_query' =>
array (size=1)
0 =>
array (size=3)
'taxonomy' => string 'qcategories' (length=11)
'field' => string 'slug' (length=4)
'terms' => string 'new' (length=3)
Looked like the code was just fine, as OP discovered there was just a little oversight in the code i.e in the plugin before registering taxonomy there was WordPress template tag if(is_admin()) which resulted the code work just fine in the Admin Panel, however when it was called in the front-end , there was no Taxonomy available for the WP_QUERY
Removing that admin_only if condition, code will just work fine.

Query WooCommerce Products based on Attribute

This one's driving me nuts.. I'm trying to query and output WooCommerce products based on a specific attribute. For example, I set up an Attribute called on, with possible values of yes or no.
I query using the following:
$args = array(
'post_type' => 'product',
'meta_key' => 'pa_on',
'meta_value' => 'yes',
'posts_per_page' => -1
);
query_posts($args);
The meta_key is crucial perhaps; if I call it on I get nothing. If I call it pa_on (because that's how I understand WooCommerce custom attributes to be constructed) I get nothing.
However, if I try a different query and use _featured, which is a standard WooCommerce custom meta thingy, it returns the relevant featured posts. Help, anyone?
I know this is an old one, but just in case someone stumbles upon it like I did today -- Woocommerce (I'm using v2.6.2) appears to store these custom attributes as taxonomies.
I suspect the correct args for the original question would look like this:
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'pa_on',
'field' => 'name',
'terms' => 'yes'
)
)
);
Using the appropriate values for my installation, it solved my problem.
For new woocommerce use:
$attribute = 'on';
$value = 'yes';
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'pa_' . $attribute,
'terms' => $value,
'field' => 'slug',
'operator' => 'IN'
)
)
);
If product attribute is saved as specific product attribute (i.e. not global), then you can't query it as taxonomy, instead you can use this snippet (copied from http://snippet.fm/snippets/query-woocommerce-products-product-specific-custom-attribute/):
// Set custom attribute name and value to search for
$attribute_name = 'color';
$attribute_value = 'green';
$serialized_value = serialize( 'name' ) . serialize( $attribute_name ) . serialize( 'value' ) . serialize( $attribute_value ); // extended version: $serialized_value = serialize( $attribute_name ) . 'a:6:{' . serialize( 'name' ) . serialize( $attribute_name ) . serialize( 'value' ) . serialize( $attribute_value ) . serialize( 'position' );
$args = array(
'post_type' => 'product',
'post_status' => 'any',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_product_attributes',
'value' => $serialized_value,
'compare' => 'LIKE',
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) {
$loop->the_post();
// do stuff here... e.g. get_the_ID()
}
wp_reset_postdata();
Guess what you need is a query with meta_query value set:
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'pa_on',
'value' => 'yes',
'compare' => '='
)
)
);
$query = new WP_Query( $args );
You can learn more about those here:
http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

Resources