php json传输被过滤,php-the_content过滤器,用于将自定义字段添加到JSON响应
我對這個用于顯示JSON API中的自定義字段的the_content過濾器感到絕望.
我正在使用此插件http://wordpress.org/plugins/json-rest-api/從自定義帖子類型獲得JSON響應.這些自定義帖子類型具有我必須在移動應用程序中顯示的自定義字段.
為了實現這一點,我編寫了以下代碼,該代碼使用the_content過濾器替換原始內容,僅使用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 = '';
$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;
}
因此,當我通過瀏覽器請求信息時,這是一個示例http://bride2be.com.mx/ceremonia/,自定義字段顯示得很好,但是當我請求JSON數據時,僅顯示HTML,而沒有自定義字段的值.
這是一個例子:
我對此不知所措,有人可以幫助我嗎?
解決方法:
您使用the_content過濾器的方式不僅在JSON API調用中,而且在各處都得到應用.
無論如何,您應該嘗試將鉤子添加到插件,而不是WordPress(至少不是第一次嘗試).
以下未經測試,但我相信是正確的軌道:
/* 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.
標簽:wordpress-plugin,wordpress,json,php
來源: https://codeday.me/bug/20191030/1966534.html
總結
以上是生活随笔為你收集整理的php json传输被过滤,php-the_content过滤器,用于将自定义字段添加到JSON响应的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python request post
- 下一篇: websocket 西部数码php_网页