星期三 , 22 1 月 2025

文章添加自定义字段代码标准模板

<?php 
/**
 * Add post meta on page 页面添加字段标准模板 (input字段为array)
 * AUthor:WP tutor
 * URI:https:www.wenxue.co
 * QQ群:307955538
 */
add_action( 'add_meta_boxes', 'wpd_add_custom_metabos' );

function wpd_add_custom_metabos() {
	//page meta 
	add_meta_box( 'wpd-page-meta', 'PAGE META', 'wpd_page_meta_cb', 'page', 'normal','default' );
	// add_meta_box( $id, $title, $callback, $screen, $context, $priority, $callback_args );
}

function wpd_page_meta_cb($post) {
	 $nonce = wp_nonce_field( __FILE__, 'page_meta_nonce' ); $page_meta = get_post_meta( $post->ID, 'wpd_page_meta', true ); ?>

	<table class="form-table">
		<tbody>
			<tr>
				<th><label for="">English Title</label></th>
				<td><input class="regular-text" type="text" name="wpd_page_meta[engTitle]" value="<?php echo $page_meta['engTitle'] ?? ''; ?>"></td>
			</tr>
		</tbody>
	</table>


	<?php 
}

function wpd_save_page_meta($post_id) {



	if (!current_user_can( 'edit_posts' )) {
		// code...
		return $post_id;
	}

	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
		return $post_id;
	}

	if (!isset($_POST['page_meta_nonce'])) {
		// code...
		return $post_id;
	}
	if (!wp_verify_nonce( $_POST['page_meta_nonce'], __FILE__ )) {
		// code...
		return $post_id;
	}

	$custom_page_fields = [
		'wpd_page_meta'
	];

	foreach ($custom_page_fields as $custom_page_field) {

		if (array_key_exists($custom_page_field,$_POST)) {
			
			$custom_page_field_data = $_POST[$custom_page_field];

			if (is_array($custom_page_field_data)) {
				$custom_page_field_data  = array_filter($custom_page_field_data); 

				if (!empty($custom_page_field_data)) {
					update_post_meta( $post_id, $custom_page_field, $custom_page_field_data );
				} else {
					delete_post_meta( $post_id, $custom_page_field );
				}
			} else {
				if (!empty($custom_page_field_data)) {
					update_post_meta( $post_id, $custom_page_field,$custom_page_field_data );
				}
			}


		}
	}

}

add_action( 'save_post', 'wpd_save_page_meta' );