正如Michal Mau指出的那样,ACF可以轻松有效地自动化此类自定义字段/元框管理。
这个manual mode 使用动作挂钩add_meta_box
和save_post
. 在本例中,您必须将指示的数组调整为array( \'place\' )
. 查看评论了解详细信息:
add_action( \'add_meta_boxes\', \'add_custom_box_wpse_94701\' );
add_action( \'save_post\', \'save_postdata_wpse_94701\', 10, 2 );
function add_custom_box_wpse_94701()
{
// Post types to insert the meta box. Adjust array <-------
foreach( array( \'post\', \'portfolio\' ) as $pt )
add_meta_box(
\'sectionid_wpse_94701\',
__( \'Custom parent\' ),
\'blogroll_box_wpse_94701\',
$pt,
\'side\'
);
}
function blogroll_box_wpse_94701()
{
global $post, $typenow;
// Get all posts of a type, excluding the current post
$args = array(
\'numberposts\' => -1,
\'post_type\' => $typenow,
\'post_status\' => \'publish,future\',
\'exclude\' => $post->ID,
);
$get_posts = get_posts( $args );
$saved = get_post_meta( $post->ID, \'custom_parent\', true);
// Security
wp_nonce_field( plugin_basename( __FILE__ ), \'noncename_wpse_94701\' );
// Dropdown
echo \'<select name="custom_parent" id="custom_parent">
<option value="">- Select -</option>\';
foreach ( $get_posts as $parent_post )
{
printf(
\'<option value="%d" %s> %s</option>\',
$parent_post->ID,
selected( $saved, $parent_post->ID, false),
$parent_post->post_title
);
}
echo \'</select>\';
}
function save_postdata_wpse_94701( $post_id, $post_object )
{
// Verify auto save
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE )
return;
// Security
if (
!isset( $_POST[\'noncename_wpse_94701\'] )
|| !wp_verify_nonce( $_POST[\'noncename_wpse_94701\'], plugin_basename( __FILE__ ) )
)
return;
// Allowed post types. Adjust array <-------
$allowed_post_types = array( \'post\', \'portfolio\' );
if ( !in_array( $post_object->post_type, $allowed_post_types ) )
return;
// Process post data
if ( isset( $_POST[\'custom_parent\'] ) )
update_post_meta( $post_id, \'custom_parent\', $_POST[\'custom_parent\'] );
else
delete_post_meta( $post_id, \'custom_parent\' );
}