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).

(See this instead: if you need to get all post meta for all posts.)

See below for a tip and usage example.

PHP

function isa_log_custom_meta( $meta_key ) {

    $args = array(
        'post_type'      => array_keys( get_post_types( array('public' => true), 'names' ) ),
        '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();
}

Tip

This searches through all pages and post types, including custom post types, but if you want to limit it to only regular posts and pages, you can change line 4 above to:

'post_type' => array('post', 'page'),

Usage

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

PHP

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]