1

I want to bulk append my custom field named 'LINK' (with data like 'http://domain.com') to the end of the post content, so I can go back to using a standard theme with no support for custom fields.

Apparently this answer to the question 'Bulk move (or copy) from a custom field to the post content?' is what I need, except it replaces the whole post-content instead of appending to it.

Can somebody help me changing this code to append to the post content?

add_shortcode('update-posts-from-custom-fields', 'upfc_fields321');
function upfc_fields321() {
$args = array(
    'meta_key' => 'custom_field',
    'meta_query' => array(
        array(
            'key'     => 'custom_field',
            'value'   => '',
            'compare' => '!=',
        ),
    ),
    'post_count' => '-1'
);
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
    $post_counter = $save_counter = $delete_counter = 0;
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        global $post; // not sure if this is needed, but it can't hurt
        echo '
        <div style="position: relative;">
            <h3 style="display: block;">' .
            the_title() . '
            </h3> 
            <div style="width: 48%; display: inline-block; float: none;">' .
            the_content() .
            '</div>';
        $post_counter++;

        $post->post_content = get_post_meta($post->ID, 'custom_field', true);
        $post->post_content_filtered = '';
        $post->post_excerpt = '';

        // uncomment next line when you are ready to commit changes
        // wp_update_post($post); $save_counter++;

        // uncomment next line if you want to delete the meta key (useful if you have too many posts and want to do them in batchces)
        // delete_post_meta($post->id, 'custom_field'); $delete_counter++;

        echo '
            <div style="width: 48%; display: inline-block; float: none">' .
            the_content() .
            '</div>
        </div>';
    }
} else {
    // no posts found
};
echo
    '<hr>Processed posts: ' . $post_counter .
    '<hr>Saved posts:' . $save_counter .
    '<hr>Deleted meta from: ' . $delete_counter . ' posts';
wp_reset_postdata() ; 
}
  • And what exactly do you want to do? What is the name of the field? How do you want it to get appended? And why is this preventing you from using some theme? – Krzysiek Dróżdż Apr 19 '19 at 4:00
  • Edited to add clarify those questions. Name of the field: 'link'. Preferably I would like run the batch once a not use custom fields anymore. My new theme doesn't have support for custom fields and I would not want to customize it. – Decio Apr 19 '19 at 12:16

Your Answer

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

Browse other questions tagged or ask your own question.