skip to Main Content

The code below produces an array of ids for all the published post types

// Test Function
add_action('wp_head', 'testa');
function testa() {
        $city = get_post_meta( 47, 'wpsl_city', true ); // Echos the correct meta for a single id

        $all_post_ids = get_posts(array(
            'fields'          => 'ids',
            'posts_per_page'  => -1,
            'post_type' => 'wpsl_stores',
            'post_status' => 'publish'
                                        )); // Echos a list of ids for CPT

        echo json_encode($all_post_ids);
}

How do I produce an array of meta values for ‘wpsl_city’ instead the post id?

Ex:

  • Right now I get [1,2,3]
    • Post ids
  • I need [New York, Chicago, Miami]
    • Corresponding post meta values for ‘wpsl_city’

2

Answers


  1. Chosen as BEST ANSWER

    Here is the final solution that worked for me:

    add_action('wp_head', 'testa');
    function testa() {
    
            $city = array();
            $all_post_ids = get_posts(array(
              'fields'         => 'ids',
              'posts_per_page' => -1,
              'post_type'      => 'wpsl_stores',
              'post_status'    => 'publish'
            )); // Echos a list of ids for CPT
    
            foreach ( $all_post_ids as $key => $post_id ) {
                $city[] = get_post_meta( $post_id, 'wpsl_city', true ); // Echos the correct meta for a single id
              }
            echo json_encode($city);
    }
    

  2. You have to iterate a loop of $all_post_ids. so you can get post id to get post meta value. try the below code.

    // Test Function
    add_action( 'wp_head', 'testa' );
    function testa() {
    
        $all_post_ids = get_posts(array(
            'fields'         => 'ids',
            'posts_per_page' => -1,
            'post_type'      => 'wpsl_stores',
            'post_status'    => 'publish'
        )); // Echos a list of ids for CPT
    
        foreach ( $all_post_ids as $key => $post_id ) {
            $city = get_post_meta( $post_id, 'wpsl_city', true ); // Echos the correct meta for a single id
            echo implode(',', $city); // assume value as array.
        }
            
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search