Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the_content filter to add custom fields to JSON response

I am little desesperate with this the_content filter for display custom field in JSON API.

I am using this plugin http://wordpress.org/plugins/json-rest-api/ to have JSON response from my custom post types. These custom post types have custom fields that I have to show in a mobile app.

To implement this I wrote this code, that use the_content filter to replace the original content to only show the custom post type with HTML tags:

add_filter( 'the_content', 'add_custom_post_fields_to_the_content' );

function add_custom_post_fields_to_the_content( $content ){

    global $post;

    $custom_fields = get_post_custom($post->ID);

    $content = '<img id="provider-logo" src="'.$custom_fields["wpcf-logo"][0].'" />';
    $content = $content.'<img id="provider-image" src="'.$custom_fields["wpcf-fotos"][0].'" />';
    $content = $content.'<h1 id="provider-name">'.$post->post_title.'</h1>';
    $content = $content.'<p id="provider-address">'.$custom_fields["wpcf-direccion"][0].'</p>';
    $content = $content.'<p id="provider-phone">'.$custom_fields["wpcf-phone"][0].'</p>';
    $content = $content.'<p id="provider-facebook">'.$custom_fields["wpcf-facebook"][0].'</p>';

    return $content;
}

So, then when I request the info via browser, this is an example http://bride2be.com.mx/ceremonia/ the custom fields are displayed well, but when I request the JSON data only shows the HTML without the values of the custom fields.

Here iss an example:

http://bride2be.com.mx/wp-json.php/posts?type=ceremonia

I am little lost with this, someone can help me?

like image 478
kentverger Avatar asked Dec 05 '25 13:12

kentverger


1 Answers

The way you're using the_content filter is being applied everywhere, not only in the JSON API call.

Anyway, you should try to add a hook to the plugin, not to WordPress (at least, not at the first try).

The following is untested, but I believe is the right track:

<?php
/* Plugin Name: Modify JSON for CPT */

add_action( 'plugins_loaded', 'add_filter_so_19646036' );

# Load at a safe point
function add_filter_so_19646036()
{
    add_filter( 'json_prepare_post', 'apply_filter_so_19646036', 10, 3 );
}

function apply_filter_so_19646036( $_post, $post, $context )
{
    # Just a guess
    if( 'my_custom_type' === $post['post_type'] )
        $_post['content'] = 'my json content';

    # Brute force debug
    // var_dump( $_post );
    // var_dump( $post );
    // var_dump( $context );
    // die();

    return $_post;
}

You'd have to inspect all three parameters to make sure this will happen in the correct post types and that you're manipulating $_post correctly.

like image 169
brasofilo Avatar answered Dec 07 '25 04:12

brasofilo