php json传输被过滤,php-the_content过滤器,用于将自定义字段添加到JSON响应
我對(duì)這個(gè)用于顯示JSON API中的自定義字段的the_content過(guò)濾器感到絕望.
我正在使用此插件http://wordpress.org/plugins/json-rest-api/從自定義帖子類型獲得JSON響應(yīng).這些自定義帖子類型具有我必須在移動(dòng)應(yīng)用程序中顯示的自定義字段.
為了實(shí)現(xiàn)這一點(diǎn),我編寫(xiě)了以下代碼,該代碼使用the_content過(guò)濾器替換原始內(nèi)容,僅使用HTML標(biāo)簽顯示自定義帖子類型:
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 = '';
$content = $content.'';
$content = $content.'
'.$post->post_title.'
';$content = $content.'
'.$custom_fields["wpcf-direccion"][0].'
';$content = $content.'
'.$custom_fields["wpcf-phone"][0].'
';$content = $content.'
'.$custom_fields["wpcf-facebook"][0].'
';return $content;
}
因此,當(dāng)我通過(guò)瀏覽器請(qǐng)求信息時(shí),這是一個(gè)示例http://bride2be.com.mx/ceremonia/,自定義字段顯示得很好,但是當(dāng)我請(qǐng)求JSON數(shù)據(jù)時(shí),僅顯示HTML,而沒(méi)有自定義字段的值.
這是一個(gè)例子:
我對(duì)此不知所措,有人可以幫助我嗎?
解決方法:
您使用the_content過(guò)濾器的方式不僅在JSON API調(diào)用中,而且在各處都得到應(yīng)用.
無(wú)論如何,您應(yīng)該嘗試將鉤子添加到插件,而不是WordPress(至少不是第一次嘗試).
以下未經(jīng)測(cè)試,但我相信是正確的軌道:
/* 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;
}
您必須設(shè)置為inspect all three parameters,以確保這會(huì)在正確的帖子類型中發(fā)生,并且您在正確地操作$_post.
標(biāo)簽:wordpress-plugin,wordpress,json,php
來(lái)源: https://codeday.me/bug/20191030/1966534.html
總結(jié)
以上是生活随笔為你收集整理的php json传输被过滤,php-the_content过滤器,用于将自定义字段添加到JSON响应的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python request post
- 下一篇: centos7搭建apache服务器(亲