0

I have a custom field value in every post. I need a rule to automatically add code to that custom field in every blog post. How can I do this ? thanks :)

2
  • Need clarification - you are saving code (what kind?) as custom field values on every post? Do you need this done in a batch or whenever posts are edited? Jul 20 '18 at 20:09
  • the custom field display just html code, it is a value. I need to envelope it with a script in every post. It should work this way : - user write a post using a front end post editor, giving the custom field a value - after post is sent, the custom field should be automatically enveloped (I guess via php) with a script that makes that field visible only for registered users. Actually I add manually the shortcodes of a content locker before and after the custom field, but I would like the procedure to be automated. Thanks
    – user147278
    Jul 20 '18 at 20:32
0

You can use the update_post_metadata hook to edit any custom field value right before it's saved to the database. For example:

function update_my_post_metadata( $check, $object_id, $meta_key, $meta_value, $prev_value ) {
    if ( $meta_key === 'MY_META_KEY' ) {
        $meta_value = 'BEFORE' . $meta_value . 'AFTER';
        update_post_meta( $object_id, $meta_key, $meta_value );
        return true;
    }
}
add_filter( 'update_post_metadata', 'update_my_post_metadata', 10, 5 );

In that example you would replace MY_META_KEY with your meta key, and BEFORE and AFTER with whatever arbitrary HTML or shortcode you wish to wrap the meta value in.

Alternately -- looking at the details in your comment -- if you're just trying to make it so that only registered users can see it, you can do that when you're outputting the meta value, like this:

if ( is_user_logged_in() ) {
    echo get_post_meta( get_the_ID(), 'MY_META_KEY', true );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.