• Hey, thanks for the great plugin you built. I was having some problems with a custom field that was getting saved with a PHP serialize array, I couldn’t read easily the content without the help of other libraries in JavaScript so I thought it will be better to fix the issue in your plugin.

    So I added these lines in the models/post.php starting at line 271

    $parsed_custom_fields = array();
    
    foreach($wp_custom_fields[$key] as $custom_field){
    
      if(is_serialized($custom_field)){
        $parsed_custom_fields[] = unserialize($custom_field);
      } else {
        $parsed_custom_fields[] = $custom_field;
      }
    
    }
    
    $this->custom_fields->$key = $parsed_custom_fields;

    Basically I’m using the WordPress built-in function is_serialized to check if the value of the custom field is a php serialize array.

    My problem started when I was using Advanced Custom Fields (ACF) and the Google Maps Custom field, but with this solution I was able to make it work. I hope you can merge this change in a new version.

    Have a good day.

    https://wordpress.org/plugins/json-api/

Viewing 5 replies - 1 through 5 (of 5 total)
  • +1 for this. I came across the same issue and opted for using php.js’s unserialize function as I didn’t want to hack the plugin. But it would be great if this could be rolled into the plugin itself so no third party JS libraries are needed, as the OP suggests.

    Thread Starter adanarchila

    (@adanarchila)

    I haven’t seen too much movement here I guess the developer is busy. I was gonna use php.js but I thought it was too much work to the browser, it was better just to server the correct content.

    A big +1!

    You are an American hero!

    Bob Gregor

    (@bobbravo2)

    Easy fix without hacking plugin code. We need to filter the post object response after the API has prepared it, using the do_action("json_api_import_wp_post", $this, $wp_post); hook.

    So, instead of hacking models/post.php, we can add the following to a theme/plugin:

    class unserialize_php_arrays_before_sending_json {
    	function __construct() {
    		add_action( 'json_api_import_wp_post',
    			array( $this, 'json_api_import_wp_post' ),
    			10,
    			2 );
    	}
    
    	function json_api_import_wp_post( $JSON_API_Post, $wp_post ) {
    		foreach ( $JSON_API_Post->custom_fields as $key => $custom_field ) {
    			$JSON_API_Post->custom_fields->$key = maybe_unserialize( $custom_field );
    		}
    	}
    }

    Now call our helper class:
    new unserialize_php_arrays_before_sending_json() to add the relevant filter.

    Please test code before using in deployment, wrote it quick to get the idea across.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Unserialize PHP Arrays before building the JSON response’ is closed to new replies.