Software Developer

Log All Posts That Have a Specific Custom Meta Field, and Log its Value

This function is just a quick loop to find all posts that have a specific custom post meta assigned to it, and get its value. Custom post meta is also known as a “custom field” for posts. This will log a list of each post that has this custom post meta field, and its value. It will be logged in your PHP error log (wherever PHP errors are logged in your server setup).

function isa_log_custom_meta( $meta_key ) {

    $args = array(
        'post_type'      => array('post'),
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'meta_key'       => $meta_key
   );
 
    $the_query = new WP_Query( $args );
 
    if ( $the_query->have_posts() ) {
 
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
 
            $value = get_post_meta( get_the_ID(), $meta_key, true );
             
            if ( $value ) {
            	
                error_log( sprintf( 'Post ID %d. %s = "%s". (%s) ', 
                                get_the_ID(),
                                $meta_key,
                                $value,
                                get_the_title()
                ) );
 
            }
        }
 
    }
     wp_reset_postdata();
}

Usage

You must pass the name of the custom meta field as an argument when using the function, like this:

isa_log_custom_meta( 'my_custom_post_meta_key' );

You must change my_custom_post_meta_key on the line above to the name of your own custom meta field.

See more:

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]