1
votes

I am using JSON API plugin for wordpress and able to add info to meta boxes (custom fields) to any custom post type but cannot do the same with taxonomies.

The code for meta boxes (custom fields) below:

// For prettier URLs, a map of post_type => (url_param_name => meta_field_name)

$CUSTOM_POST_META_FIELDS = array(
'classifieds' => array(
'price' => 'wpcf-price-with-discount',
'condition' => 'wpcf-condition'
)
);

// Handle metadata
global $CUSTOM_POST_META_FIELDS;
if ($this->id && !empty($CUSTOM_POST_META_FIELDS[$wp_values['post_type']])) {
  foreach ($CUSTOM_POST_META_FIELDS[$wp_values['post_type']] as $param => $meta) {
    update_post_meta($this->id, $meta, $values[$param]);
  }
}

Can you suggest the similar code for adding taxonomies terms please? For example post type 'classifieds' has got taxonomy 'type' and I want to add any terms to it.

2

2 Answers

0
votes

also as an additional idea is to somehow amend the second part of the code after //Handle metadata

 function set_custom_taxonomies($type) {
global $json_api;
$taxonomies = get_taxonomies(array(
  'object_type' => array($type),
  'public'   => true,
  '_builtin' => false
), 'objects');
foreach ($taxonomies as $taxonomy_id => $taxonomy) {
  $taxonomy_key = "taxonomy_$taxonomy_id";
  if (!$json_api->include_value($taxonomy_key)) {
    continue;
  }
  $taxonomy_class = $taxonomy->hierarchical ? 'JSON_API_Category' : 'JSON_API_Tag';
  $terms = get_the_terms($this->id, $taxonomy_id);
  $this->$taxonomy_key = array();
  if (!empty($terms)) {
    $taxonomy_terms = array();
    foreach ($terms as $term) {
      $taxonomy_terms[] = new $taxonomy_class($term);
    }
    $this->$taxonomy_key = $taxonomy_terms;
  }
}
 }

Thank you in advance!

0
votes

I used the following to set a specific category when posting custom post type through JSON API. Can be modified to get array from $values, then get array of ids for all terms.

Place following in the function save() of controllers/posts.php

inside:

if (isset($wp_values['ID'])) {

following both:

$this->id = wp_update_post($wp_values);
$this->id = wp_insert_post($wp_values);

//First get the id of the category(custom taxonomy) you want this post to appear. I
$term = term_exists( 'slug', 'type' ); //returns term's id if it exists

wp_set_post_terms($this->id,$term,'your_custom_taxonomy');