I’ve set up Custom Fields that accept a URL to a social media site, I would like to then check and see if the field contains http://
and if it does not, add it before saving to the db.
// 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 }
When I var_dump($account)
it gives me the correctly adjusted urls here.
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' );
And using the same logic that works in the callback function above, this does not save the adjusted url in the db. My guess is that the data structure that I retrieve from $_POST["accounts"]
is not the same as the serialized data I fetch from the callback function. Unfortunately I am not sure how to get a look at that data to determine the correct structure to parse the URL.
In your loop you are doing
This does not update the original value in array 🙂
As Hanky Panky has noted above, I forgot to update the value of the array. For completeness, here is what the functional foreach loop looks like:
Please notice the subtle change of the added
&
in the foreach loop:foreach ($accounts as &$account) {
Explained: http://php.net/manual/en/language.references.pass.php