3

我对这个the_content在 JSON API 中显示自定义字段的过滤器有点绝望。

我正在使用这个插件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自定义字段。

这是一个例子:

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

我对此有点迷茫,有人可以帮助我吗?

4

1 回答 1

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

您必须检查所有三个参数以确保这将在正确的帖子类型中发生并且您正在$_post正确操作。

于 2013-10-29T08:21:15.713 回答