the_content过滤器,用于向JSON响应添加自定义字段

时间:2013-10-28 22:12:51

标签: php json wordpress wordpress-plugin

对于JSON API中的显示自定义字段,我对这个the_content过滤器很不感兴趣。

我正在使用此插件http://wordpress.org/plugins/json-rest-api/来获取自定义帖子类型的JSON响应。这些自定义帖子类型包含我必须在移动应用中显示的自定义字段。

为了实现这一点,我编写了这段代码,使用the_content filter替换原始内容,仅显示带有HTML标记的自定义帖子类型:

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;
}

那么,当我通过浏览器请求信息时,这是一个示例http://bride2be.com.mx/ceremonia/自定义字段显示良好,但是当我请求JSON数据时,只显示没有自定义字段值的HTML。 / p>

以下是一个例子:

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

我很少迷失,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:4)

您正在使用the_content过滤器的方式无处不在,而不仅仅是在JSON API调用中。

无论如何,你应该尝试在插件中添加一个钩子,而不是WordPress(至少在第一次尝试时没有)。

以下是未经测试的,但我认为是正确的轨道:

<?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;
}

您必须inspect all three parameters确保在正确的帖子类型中发生这种情况并且您正确操作$_post