我已经设置了接受社交媒体网站 URL 的自定义字段,然后我想检查该字段是否包含 http://
,如果不包含,请添加在保存到数据库之前。
// Add Social Media Meta Boxes
function add_social_box()
{
add_meta_box( 'social-media',
__( 'Social Media'), 'social_meta_box_callback', 'page', 'advanced', 'high');
}
add_action( 'add_meta_boxes', 'add_social_box' );
function social_meta_box_callback( $post ) {
// Add a nonce field so we can check for it later.
wp_nonce_field( 'social_save', 'social_meta_box_nonce' ); ?>
<div id="meta-inner">
<?php
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$accounts = get_post_meta( $post->ID, 'accounts', true);
// foreach ($accounts as $account) {
// $parsed = parse_url($account);
// if (empty($parsed['scheme'])) {
// $account = 'http://' . ltrim($account, '/');
// }
// var_dump($account);
// }
?>
<div>
<label for="facebook">Facebook</label>
<input type="text" id="facebook" name="accounts[facebook]" value="<?php echo esc_attr( $accounts["facebook"] ) ?>" />
</div>
<div>
<label for="twitter">Twitter</label>
<input type="text" id="twitter" name="accounts[twitter]" value="<?php echo esc_attr( $accounts["twitter"] ) ?>" />
</div>
</div>
<?php }
当我var_dump($account)
时,它会在此处提供正确调整的网址。
function social_save_postdata( $post_id ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
// if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
// return;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
// if ( !isset( $_POST['menu_meta_box_nonce'] ) )
// return;
// if ( !wp_verify_nonce( $_POST['social_meta_box_nonce'], 'social_save' ) )
// return;
$accounts = $_POST["accounts"];
foreach ($accounts as $account) {
$parsed = parse_url($account);
if (empty($parsed['scheme'])) {
$account = 'http://' . ltrim($account, '/');
}
update_post_meta($post_id,'accounts',$accounts);
}
}
add_action( 'save_post', 'social_save_postdata' );
并且使用与上面回调函数中相同的逻辑,这不会将调整后的网址保存在数据库中。我的猜测是,我从 $_POST["accounts"]
检索的数据结构与我从回调函数获取的序列化数据不同。不幸的是,我不确定如何查看该数据以确定解析 URL 的正确结构。
最佳答案
在你的循环中你正在做
$account = 'http://' . ltrim($account, '/');
这不会更新数组中的原始值:)
关于php - 在保存之前操作数组的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33794401/