How to display all Wordpress posts with own custom key

Viewed 83

I'd like to get and display all posts by my own custom key "expiration_date".

I use WCK plugin for adding my custom keys. I've added two fields: expiration_date and price.

I tried to write it by myself and I created my owf function 'courses_by_date' in template function.php file and display courses_by_date(); in content-page.php file, when I want to display all posts with added these above two fields.

Very important: some posts may have several pairs of fields: expiration_date and price.

Now, I can display only the first pair of these fields of each post with these keys.

function courses_by_date() {    
    $args = array("posts_per_page" => 20, "meta_key" => 'expiration_date');
    
  $posts_array = get_posts($args);
  foreach($posts_array as $i => $post)
  {
    echo $i . " <a class='title' href='https://post-url.com'>" . $post->post_title . "</a> | " . $post->expiration_date . ", price: " . $post->price . " EUR " . "<br>";        
  }
}
1 Answers

You can pass increment params at end of the meta key. check below code.

function kursy_wg_daty() {
    $a = 0;

    echo "<ul>";
    while($a < 20) {
        if($a == 0) {
            $args = array("posts_per_page" => 20, "meta_key" => 'expiration_date');
            $posts_array = get_posts($args);
            foreach($posts_array as $post){
                echo "<li> <a class='title' href=" . post_permalink($post) . ">" . $post->post_title . "</a> | " . $post->expiration_date . ", price: " . $post->price . " zł " . "</li>";
            }
        } else {
            $args = array("posts_per_page" => 20, "meta_key" => "expiration_date" . "_" . $a);
            $posts_array = get_posts($args);
            foreach($posts_array as $post) {

                $expiration_date = get_post_meta( $post->ID, 'expiration_date_'.$a, true );
                $price = get_post_meta( $post->ID, 'price_'.$a, true );

                echo "<li> <a class='title' href=" . post_permalink($post) . ">" . $post->post_title . "</a> | " . $expiration_date . ", price: " . $price . " zł " . "</li>";
            }
        }
        $a++;
    }
    echo "</ul>";
}
Related