wp_json_encode()
概述
wp_json_encode() 是 WordPress 核心函数,用于将变量编码为 JSON 字符串,并提供额外的可靠性检查。它基于 PHP 的 json_encode() 函数,但在编码失败时会尝试通过 _wp_json_sanity_check() 进行修复。
关键要点
- 函数签名:wp_json_encode( $value, $flags = 0, $depth = 512 )
- 参数:$value(必需,要编码的变量,通常为数组或对象),$flags(可选,传递给 json_encode() 的选项,默认 0),$depth(可选,遍历 $value 的最大深度,必须大于 0,默认 512)
- 返回值:成功时返回 JSON 编码字符串,失败时返回 false
- 内部机制:先调用 json_encode(),若失败则使用 _wp_json_sanity_check() 清理数据后重试
- 兼容性:从 WordPress 4.1.0 引入,6.5.0 版本重命名参数以与 PHP 保持一致
代码示例
function get_json() {
$out = array();
$out['options'] = array( 'option-1', 'option-2' );
$out['content'] = 'content example';
return wp_json_encode( $out );
} Encodes a variable into JSON, with some confidence checks.
Parameters
$valuemixedrequired-
Variable (usually an array or object) to encode as JSON.
$flagsintoptional-
Options to be passed to json_encode(). Default 0.
$depthintoptional-
Maximum depth to walk through $value. Must be greater than 0.
Default:
512
Return
string|false The JSON encoded string, or false if it cannot be encoded.
Source
function wp_json_encode( $value, $flags = 0, $depth = 512 ) {
$json = json_encode( $value, $flags, $depth );
// If json_encode() was successful, no need to do more confidence checking.
if ( false !== $json ) {
return $json;
}
try {
$value = _wp_json_sanity_check( $value, $depth );
} catch ( Exception $e ) {
return false;
}
return json_encode( $value, $flags, $depth );
}
Related
| Used by | Description |
|---|---|
WP_Interactivity_API::add_load_on_client_navigation_attribute_to_script_modules()wp-includes/interactivity-api/class-wp-interactivity-api.php |
Adds the |
wp_enqueue_command_palette_assets()wp-includes/script-loader.php |
Enqueues the assets required for the Command Palette. |
wp_print_speculation_rules()wp-includes/speculative-loading.php |
Prints the speculation rules. |
wp_unique_id_from_values()wp-includes/functions.php |
Generates a unique ID based on the structure and values of a given array. |
WP_Script_Modules::print_script_module_data()wp-includes/class-wp-script-modules.php |
Print data associated with Script Modules. |
wp_interactivity_data_wp_context()wp-includes/interactivity-api/interactivity-api.php |
Generates a |
WP_Script_Modules::print_import_map()wp-includes/class-wp-script-modules.php |
Prints the import map using a script tag with a type=”importmap” attribute. |
inject_ignored_hooked_blocks_metadata_attributes()wp-includes/block-template-utils.php |
Inject ignoredHookedBlocks metadata attributes into a template or template part. |
WP_REST_Font_Faces_Controller::prepare_item_for_database()wp-includes/rest-api/endpoints/class-wp-rest-font-faces-controller.php |
Prepares a single font face post for creation. |
WP_REST_Font_Families_Controller::prepare_item_for_database()wp-includes/rest-api/endpoints/class-wp-rest-font-families-controller.php |
Prepares a single font family post for create or update. |
wp_remove_surrounding_empty_script_tags()wp-includes/script-loader.php |
Removes leading and trailing _empty_ script tags. |
_wp_filter_post_meta_footnotes()wp-includes/blocks.php |
Strips all HTML from the content of footnotes, and sanitizes the ID. |
wp_attach_theme_preview_middleware()wp-includes/theme-previews.php |
Adds a middleware to |
wp_block_theme_activate_nonce()wp-includes/theme-previews.php |
Set a JavaScript constant for theme activation. |
WP_Style_Engine_Processor::combine_rules_selectors()wp-includes/style-engine/class-wp-style-engine-processor.php |
Combines selectors from the rules store when they have the same styles. |
wp_add_global_styles_for_blocks()wp-includes/global-styles-and-settings.php |
Adds global style rules to the inline style for each block. |
WP_REST_Global_Styles_Controller::prepare_item_for_database()wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php |
Prepares a single global styles config for update. |
wp_generate_block_templates_export_file()wp-includes/block-template-utils.php |
Creates an export of the current templates and template parts from the site editor at the specified path in a ZIP file. |
wp_filter_global_styles_post()wp-includes/kses.php |
Sanitizes global styles user content removing unsafe rules. |
block_editor_rest_api_preload()wp-includes/block-editor.php |
Preloads common data used with the block editor by specifying an array of REST API paths that will be preloaded for a given block editor context. |
rest_validate_enum()wp-includes/rest-api.php |
Validates that the given value is a member of the JSON Schema “enum”. |
WP_Application_Passwords_List_Table::print_js_template_row()wp-admin/includes/class-wp-application-passwords-list-table.php |
Prints the JavaScript template for the new row item. |
serialize_block_attributes()wp-includes/blocks.php |
Given an array of attributes, returns a string in the serialized attributes format prepared for post content. |
WP_Site_Health::wp_cron_scheduled_check()wp-admin/includes/class-wp-site-health.php |
Runs the scheduled event to check and update the latest site health status for the website. |
enqueue_editor_block_styles_assets()wp-includes/script-loader.php |
Function responsible for enqueuing the assets required for block styles functionality on the editor. |
_jsonp_wp_die_handler()wp-includes/functions.php |
Kills WordPress execution and displays JSONP response with an error message. |
wp_ajax_health_check_site_status_result()wp-admin/includes/ajax-actions.php |
Handles site health check to update the result status via AJAX. |
_json_wp_die_handler()wp-includes/functions.php |
Kills WordPress execution and displays JSON response with an error message. |
wp_default_packages_vendor()wp-includes/script-loader.php |
Registers all the WordPress vendor scripts that are in the standardized |
wp_default_packages_inline_scripts()wp-includes/script-loader.php |
Adds inline scripts required for the WordPress JavaScript packages. |
wp_tinymce_inline_scripts()wp-includes/script-loader.php |
Adds inline scripts required for the TinyMCE in the block editor. |
the_block_editor_meta_boxes()wp-admin/includes/post.php |
Renders the meta boxes forms. |
wp_create_user_request()wp-includes/user.php |
Creates and logs a user request to perform a specific action. |
WP_Privacy_Policy_Content::notice()wp-admin/includes/class-wp-privacy-policy-content.php |
Adds a notice with a link to the guide when editing the privacy policy page. |
wp_privacy_generate_personal_data_export_file()wp-admin/includes/privacy-tools.php |
Generate the personal data export file. |
wp_start_scraping_edited_file_errors()wp-includes/load.php |
Starts scraping edited file errors. |
wp_finalize_scraping_edited_file_errors()wp-includes/load.php |
Finalizes scraping for edited file errors. |
wp_enqueue_code_editor()wp-includes/general-template.php |
Enqueues assets needed by the code editor for the given settings. |
WP_Widget_Media_Gallery::enqueue_admin_scripts()wp-includes/widgets/class-wp-widget-media-gallery.php |
Loads the required media files for the media manager and scripts for media widgets. |
WP_Widget_Custom_HTML::enqueue_admin_scripts()wp-includes/widgets/class-wp-widget-custom-html.php |
Loads the required scripts and styles for the widget control. |
WP_Customize_Date_Time_Control::content_template()wp-includes/customize/class-wp-customize-date-time-control.php |
Renders a JS template for the content of date time control. |
_WP_Editors::default_settings()wp-includes/class-wp-editor.php |
Returns the default TinyMCE settings. |
WP_Widget_Text::enqueue_admin_scripts()wp-includes/widgets/class-wp-widget-text.php |
Loads the required scripts and styles for the widget control. |
WP_Widget_Media_Audio::enqueue_admin_scripts()wp-includes/widgets/class-wp-widget-media-audio.php |
Loads the required media files for the media manager and scripts for media widgets. |
WP_Widget_Media_Video::enqueue_admin_scripts()wp-includes/widgets/class-wp-widget-media-video.php |
Loads the required scripts and styles for the widget control. |
WP_Widget_Media_Image::enqueue_admin_scripts()wp-includes/widgets/class-wp-widget-media-image.php |
Loads the required media files for the media manager and scripts for media widgets. |
WP_Community_Events::maybe_log_events_response()wp-admin/includes/class-wp-community-events.php |
Logs responses to Events API requests. |
WP_Customize_Manager::save_changeset_post()wp-includes/class-wp-customize-manager.php |
Saves the post for the loaded changeset. |
wp_localize_jquery_ui_datepicker()wp-includes/script-loader.php |
Localizes the jQuery UI datepicker. |
WP_Customize_Widgets::filter_dynamic_sidebar_params()wp-includes/class-wp-customize-widgets.php |
Inject selective refresh data attributes into widget container elements. |
WP_Customize_Site_Icon_Control::content_template()wp-includes/customize/class-wp-customize-site-icon-control.php |
Renders a JS template for the content of the site icon control. |
WP_Customize_Selective_Refresh::export_preview_data()wp-includes/customize/class-wp-customize-selective-refresh.php |
Exports data in preview after it has finished rendering so that partials can be added at runtime. |
WP_Customize_Manager::customize_pane_settings()wp-includes/class-wp-customize-manager.php |
Prints JavaScript settings for parent window. |
WP_REST_Server::serve_request()wp-includes/rest-api/class-wp-rest-server.php |
Handles serving a REST API request. |
WP_REST_Server::json_error()wp-includes/rest-api/class-wp-rest-server.php |
Retrieves an appropriate error representation in JSON. |
WP_Customize_Nav_Menus::export_preview_data()wp-includes/class-wp-customize-nav-menus.php |
Exports data from PHP to JS. |
WP_Customize_Nav_Menus::filter_wp_nav_menu()wp-includes/class-wp-customize-nav-menus.php |
Prepares wp_nav_menu() calls for partial refresh. |
WP_Customize_Nav_Menus::enqueue_scripts()wp-includes/class-wp-customize-nav-menus.php |
Enqueues scripts and styles for Customizer pane. |
WP_List_Table::ajax_response()wp-admin/includes/class-wp-list-table.php |
Handles an incoming ajax request (called from admin-ajax.php) |
WP_List_Table::_js_vars()wp-admin/includes/class-wp-list-table.php |
Sends required variables to JavaScript land. |
admin_color_scheme_picker()wp-admin/includes/misc.php |
Displays the default administration color scheme picker (Used in user-edit.php). |
wp_color_scheme_settings()wp-admin/includes/misc.php |
|
WP_Internal_Pointers::print_js()wp-admin/includes/class-wp-internal-pointers.php |
Prints the pointer JavaScript data. |
compression_test()wp-admin/includes/template.php |
Tests support for compressing JavaScript from PHP. |
WP_Themes_List_Table::_js_vars()wp-admin/includes/class-wp-themes-list-table.php |
Send required variables to JavaScript land |
media_upload_form()wp-admin/includes/media.php |
Outputs the legacy media upload form. |
media_send_to_editor()wp-admin/includes/media.php |
Adds image HTML to editor. |
wp_ajax_upload_attachment()wp-admin/includes/ajax-actions.php |
Handles uploading attachments via AJAX. |
wp_ajax_menu_get_metabox()wp-admin/includes/ajax-actions.php |
Handles for retrieving menu meta boxes via AJAX. |
wp_ajax_wp_link_ajax()wp-admin/includes/ajax-actions.php |
Handles internal linking via AJAX. |
wp_ajax_autocomplete_user()wp-admin/includes/ajax-actions.php |
Handles user autocomplete via AJAX. |
_wp_ajax_menu_quick_search()wp-admin/includes/nav-menu.php |
Prints the appropriate response to a menu quick search. |
options_general_add_js()wp-admin/includes/options.php |
Display JavaScript on the page. |
WP_Customize_Manager::customize_preview_settings()wp-includes/class-wp-customize-manager.php |
Prints JavaScript settings for preview frame. |
WP_Customize_Manager::wp_die()wp-includes/class-wp-customize-manager.php |
Custom wp_die wrapper. Returns either the standard message for UI or the Ajax message. |
_wp_customize_loader_settings()wp-includes/theme.php |
Adds settings for the customize-loader script. |
wp_send_json()wp-includes/functions.php |
Sends a JSON response back to an Ajax request. |
WP_Widget_Categories::widget()wp-includes/widgets/class-wp-widget-categories.php |
Outputs the content for the current Categories widget instance. |
WP_Widget_Archives::widget()wp-includes/widgets/class-wp-widget-archives.php |
Outputs the content for the current Archives widget instance. |
wp_version_check()wp-includes/update.php |
Checks WordPress version against the newest version. |
wp_update_plugins()wp-includes/update.php |
Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
wp_update_themes()wp-includes/update.php |
Checks for available updates to themes based on the latest versions hosted on WordPress.org. |
wp_plupload_default_settings()wp-includes/media.php |
Prints default Plupload arguments. |
wp_playlist_shortcode()wp-includes/media.php |
Builds the Playlist shortcode output. |
WP_Scripts::localize()wp-includes/class-wp-scripts.php |
Localizes a script, only if the script has already been added. |
WP_Customize_Widgets::export_preview_data()wp-includes/class-wp-customize-widgets.php |
Communicates the sidebars that appeared on the page at the very end of the page, and at the very end of the wp_footer, |
WP_Customize_Widgets::enqueue_scripts()wp-includes/class-wp-customize-widgets.php |
Enqueues scripts and styles for Customizer panel and export data to JavaScript. |
wp_default_scripts()wp-includes/script-loader.php |
Registers all WordPress scripts. |
_WP_Editors::editor_settings()wp-includes/class-wp-editor.php |
|
_WP_Editors::wp_mce_translation()wp-includes/class-wp-editor.php |
Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(), or as JS snippet that should run after tinymce.js is loaded. |
Skip to note 2 content
Kamal Hosen
function get_json() { $out = array(); $out['options'] = array( 'option-1', 'option-2' ); $out['content'] = 'content example'; return wp_json_encode( $out ); }