let’s make something together

Give us a call or drop by anytime, we endeavour to answer all enquiries within 24 hours on business days.

Find us

1245 Northern Ct, Hixson, Tennessee, 37345

Email us

support@freelancersdev.com

Phone support

Phone: +1-312-701-3057

Import JSON files in WordPress

  • By Nikki Bela
  • March 18, 2021
  • 18 Views

JSON REST API is increasingly becoming a thing in WordPress in recent times. It is more than an adaptation to the site where covering the left-over data is improvised through the JSON-powered world and its relatable features.

What do you know about JSON?

JSON or JavaScript Object Notation is a standard format that represents data that most devices, languages, and protocols are able to understand. In simple words, it is a representation that is common in many technical devices. There have been several instances where JSON has become more popular as it is faster and east to read and write. It won’t be wrong to say JSON has become the successor of the XML. For example, suppose there is a person with many attributes. Therefore, the JSON object of that person will be represented in the following form –

 {

  “first-name”: “Tomaz”,

  “last-name”: “Zaman”,

  “age”: 32,

  “address”: {

    “country”: “Slovenia”

  },

  “hobbies”: [

    “skydiving”,

    “movies”

  ]

}

The absence of Plug-ins: 

WordPress is not able to handle JSON data well if the WP-REST-API plug-in is not available. It is mainly because of the submission of data type as – x-www-form-URL encoded. Furthermore, it means that when you submit a post, the data will easily get vanished and encoded in the URL. Though it the actual behavior of the HTML but here we are informing you about the data and not the forms.  

There will a need for some URL in order to import data from our external services. WordPress has been providing wp_ajax, but since it is an internal service, it does not have a vague to where the ajax endpoint lies. Thus, there was a need for the URL code that would be like – http://example.com/wp-admin/admin-ajax.php?action=your_import_action_name.

While talking about code and developers and other technical stuff, you need to refer to a real example. Here we will show you how to import Codeable developers into WordPress from our custom application.  

Registering of hooks: 

There will be a need to create two hooks or actions to maximize the potential of WordPress AJAX. It will be responsible for triggering the import and function. In this, you will be asked to put in the codes as shown below in functions.php or other files that have got the theme or the plug-in. 

add_action( ‘wp_ajax_import_developer’, ‘import_developer’ );

add_action( ‘wp_ajax_nopriv_import_developer’, ‘import_developer’ );

These are the two actions for which you need to define the function that is hook into it –

function import_developer() {

  $developer_data = json_decode( file_get_contents( ‘php://input’ ) );

  if ( compare_keys() ) {                             

    insert_or_update( $developer_data );

  }

  wp_die();

}

Here, the important functions are read as –

  • 3rd Line – It reads the request body, assigns the format to $developer_data after decoding it.
  • 5th Line – It performs the security check.
  • 6th Line – It passes the data to another function. Furthermore, it may create a new developer record or can even update the existing one.   
  • 9th Line – It is registered that nothing is being processed once we import the developer.

As you proceed through the function, the next step will be importing the developer. Here you will read about that too.

Updating or inserting a record: 

Before we move any further, here is a look at what our JSON representation of a developer will be shown as –

{

    “id”: “1”,

    “full_name”: “Tomaz Zaman”,

    “bio”: “Codeable founder”,

    “tags”: [

        “CSS”,

        “HTML”,

        “PHP”,

        “WordPress”

    ]

}

Here, while importing, full_name is represented as the post title, and the bio is the post content and the tags.

To check the action that you have to perform between the two, you need to check if the record exists or not. For that, you will have to use the custom field as – developer_id in the custom post. You can also insert some additional functions for the display of themes which is optional. However, there is no need for additional fields as some attributes will not be modified n WordPress. The custom field will be named JSON. At the same time, you should feel free to use as much of the custom field as per your requirements if there’s any problem.

Here is the complete code with explanation given below –

function insert_or_update($developer_data) {

  if ( ! $developer_data)

    return false;

  $args = array(

    ‘meta_query’ => array(

      array(

        ‘key’ => ‘developer_id’,

        ‘value’ => $developer_data->id

      )

    ),

    ‘post_type’ => ‘developer’,

    ‘post_status’ => array(‘publish’, ‘pending’, ‘draft’, ‘auto-draft’, ‘future’, ‘private’, ‘inherit’),

    ‘posts_per_page’ => 1

  );   

  $developer = get_posts( $args );

  $developer_id = ”;

  if ( $developer )

    $developer_id = $developer[0]->ID;

  $developer_post = array(

    ‘ID’ => $developer_id,

    ‘post_title’ => $developer_data->full_name,

    ‘post_content’ => $developer_data->bio,

    ‘post_type’ => ‘developer’,

    ‘post_status’ => ( $developer ) ? $developer[0]->post_status : ‘publish’

  );

  $developer_id = wp_insert_post( $developer_post );

  if ( $developer_id ) {

    update_post_meta( $developer_id, ‘developer_id’, $developer_data->id );

    update_post_meta( $developer_id, ‘json’, addslashes( file_get_contents( ‘php://input’ ) ) );

    wp_set_object_terms( $developer_id, $developer_data->tags, ‘developer_tag’ );

  }

  print_r( $developer_id );

}

In the 3rd line of the code, we have checked that if $developer_data contains the data. After that, we will prepare an argument for the query, which will either return one record or no record at all. As soon as it fetches an existing record, it assigns the ID to $developer_id in the 23rd line, which is equally important. It creates a new record or updates an existing one when you type wp_insert_post.  

As it is done, you will be required to update the custom field via update_post_meta. For convenience, you can save raw JSON data into the field. Also, as we use custom taxonomy for the developers, it will be necessary to update the developer_tag. It has the key feature to automatically update or create important tags. 

Lastly, our external application will be in need to know that everything went smoothly. For this, it will be essential to give a printout for the WordPress ID in the record.  

Nikki Bela

Nikki Bela is the Senior Content Writer and Editor at freelancersdev.com. She has been working with us for more than 5 years and is well-versed in writing, editing and managing various marketing content for our blogs. Also, she has detailed knowledge about SEO, PPC and other online marketing tools on the internet.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Consultation