1

I'm working on a Movie site in WordPress and I'm developing a plugin to fill in fields on my custom post type from IMDb. I've created a search form meta box and using AJAX I can update the values of input and textarea fields because you can just set those with .val(newvalue). Is it possible to set/add custom taxonomy values, like Tags, as well? I'd like to be able to add values to my custom taxonomy 'Actors' as well but it doesn't appear to be a simple form field.

enter image description here

plugin.php

function imdb_ajax_action(){
    if (!wp_verify_nonce($data['imdb_ajax_nonce'], basename(__FILE__))){
        die(-1);
    }

    $api_meta = null;

    if ($data['imdb-box-title']){
        $search_title = $data['imdb-box-title'];
        $api_url = 'MY_API_URL';
        $api_response = json_decode(file_get_contents($api_url));

        $api_meta = [
            'year' => $api_response->Year,
            'synopsis' => $api_response->Plot,
            'director' => $api_response->Director,
            'runtime' => $api_response->Runtime,
            'rating' => $api_response->imdbRating,
        ];
    }

    print json_encode($api_meta);
    wp_die();
}

imdb-ajax.js

jQuery(document).ready(function($) {
  $('body').on('click', '#scrape-imdb', function (e) {
    e.preventDefault();
    var $me = $(this),
    action = 'imdb_ajax_action';

    var data = $.extend(true, $me.data(), {
     action: action,
     form_data: $('#post').serializeArray()
    });

    $.post(ajaxurl, data, function (response) {
      if (response == '0' || response == '-1'){
        console.error('IMDb AJAX error');
        console.log(response);
      } else {
        console.log('AJAX successful');
        var movie_data = $.parseJSON(response);

        $("div[data-name='year']").find('input').val(movie_data.year);
        $("div[data-name='synopsis']").find('textarea').val(movie_data.synopsis);
        $("div[data-name='director']").find('input').val(movie_data.director);
        $("div[data-name='runtime']").find('input').val(movie_data.runtime);
        $("div[data-name='imdb_rating']").find('input').val(movie_data.rating);
      }
    });
  })
});
  • The input for tags is fairly straightforward, you could add the actors, comma separated, to the input element, and then 'click' the Add button with jQuery, then WordPress will take care of actually adding/selecting the terms. – Jacob Peattie Feb 22 '18 at 13:43
  • 1
    @JacobPeattie you're right, that works quite well. Thanks! – Robert Feb 22 '18 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.