Search code examples
wordpressmeta-key

how to get postmeta key value for all post?


I want to get post_meta value of all the posts.

For the database table wp_postmeta, I want to get meta values of key '_job_hourly_fee' for all the posts, not only single post. Don't know how to do. thanks in advance.


Solution

  • This will give you an array of all of the values that exist for that field. You could adapt it to provide 'post_title : _job_hourly_fee value'. Simply put this code in your theme's (or child theme's) functions.php and add the shortcode: [job_hourly_fee_values] to your post or page HTML content where you want the result to appear.

    <?php
    function get_fee_values(){
        $jhf_values = array('');//AN EMPTY ARRAY TO STORE THE VALUES GATHERED
        $the_query = new WP_Query( 'post_type=post' );//CHANGE TO CUSTOM POST TYPE IF REQUIRED
        if ( $the_query->have_posts() ) {
            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                $the_answer=get_post_meta($the_query->ID, '_job_hourly_fee' , true);//'TRUE' WILL RETURN ONLY ONE VALUE FOR EACH POST.
                $the_answer=trim($the_answer);//REMOVE UNWANTED WHITESPACE FROM BEGINNING AND END 
                array_push($jhf_values, $the_answer);//ADD THE RESULT TO THE EMPTY ARRAY
            }
        }
        $jhf_values = array_unique($jhf_values);//NOW WEVE GOT ALL THE VALUES, WE CAN REMOVE DUPLICATES
        $jhf_values = sort($jhf_values);//AND WE CAN PUT THEM IN ORDER
        //NOW WE CAN RUN THROUGH THE ARRAY AND DO SOMETHING WITH EACH OBJECT...
        foreach ($jhf_values as $value) { 
        echo "<p>".$value."</p>";
        }
    }
    ?>
    <?php
    add_shortcode('job_hourly_fee_values', 'get_fee_values');?> //PLACE SHORTCODE [job_hourly_fee_values] IN YOUR POST OR PAGE HTML CONTENT WHERE YOU WANT THE RESULT TO APPEAR
    ?>