【问题标题】:the_content filter to add custom fields to JSON responsethe_content 过滤器将自定义字段添加到 JSON 响应
【发布时间】:2013-11-07 21:19:51
【问题描述】:

我对这个用于在 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。

这是一个例子:

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

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

【问题讨论】:

  • 扫描插件中的钩子,没看过多少,但这个可能有帮助:apply_filters( 'json_prepare_{$this-&gt;type}', $_post, $post, $context );
  • 我在插件代码 'content' => apply_filters( 'the_content', $post['post_content'] ) 中发现了这个,所以我认为该插件实现了该过滤器。
  • 我没有安装插件来帮助更多...检查this

标签: php json wordpress


【解决方案1】:

您使用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

【讨论】:

  • 谢谢很多,效果很好:),最后一个问题,你在哪里找到 json_prepare_post 过滤器的文档?
  • Digging into the source。一个不错的代码编辑器;全局搜索apply_filters(或do_action);找到我们想要的嫌疑人;编写一个自定义钩子。第一枪就成功了!是的,我开始擅长这个了;)
猜你喜欢
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多