最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Get a list of posts with associated meta_value

programmeradmin0浏览0评论

Recently I began to use the Custom Fields. I would like to display a listing of posts which contains the meta_key "oldtimer" and also get the corresponding meta_value.

Here is the expected result:

<table>
<tr>
    <td>Title of post 1</td>
    <td>OLD-39283</td>
</tr>
<tr>
    <td>Title of post 2</td>
    <td>OLD-22445</td>
</tr>
<tr>
    <td>Title of post 3</td>
    <td>OLD-32145</td>
</tr></table>

Here is the PHP code I have for now. I don't know how to get the meta_value for each post:

$args =
    array(
    'posts_per_page'         => -1,
    'order'                  => 'ASC',
    'orderby'                => 'title',
    'meta_key'               => 'oldtimer'
);

$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
    echo '<table>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<tr><td><a href="'. get_the_permalink() .'">' . get_the_title() . '</td>';
        echo '<td>meta_key</td></tr>';
    }
    echo '</table>';

    /* Restore original Post Data */
    wp_reset_postdata();
    } else {
    // no posts found
}

Here is the information on SQL side:

Is anyone has an idea? Any suggestion about this will be much appreciated.

Recently I began to use the Custom Fields. I would like to display a listing of posts which contains the meta_key "oldtimer" and also get the corresponding meta_value.

Here is the expected result:

<table>
<tr>
    <td>Title of post 1</td>
    <td>OLD-39283</td>
</tr>
<tr>
    <td>Title of post 2</td>
    <td>OLD-22445</td>
</tr>
<tr>
    <td>Title of post 3</td>
    <td>OLD-32145</td>
</tr></table>

Here is the PHP code I have for now. I don't know how to get the meta_value for each post:

$args =
    array(
    'posts_per_page'         => -1,
    'order'                  => 'ASC',
    'orderby'                => 'title',
    'meta_key'               => 'oldtimer'
);

$the_query = new WP_Query($args);
// The Loop
if ( $the_query->have_posts() ) {
    echo '<table>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<tr><td><a href="'. get_the_permalink() .'">' . get_the_title() . '</td>';
        echo '<td>meta_key</td></tr>';
    }
    echo '</table>';

    /* Restore original Post Data */
    wp_reset_postdata();
    } else {
    // no posts found
}

Here is the information on SQL side:

Is anyone has an idea? Any suggestion about this will be much appreciated.

Share Improve this question asked Sep 4, 2019 at 20:06 lapulpelapulpe 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

You can just fetch the post meta manually within the loop as follows:

get_post_meta( get_the_ID(), 'oldtimer', true );

That should get you the correct value. Hope it helps

发布评论

评论列表(0)

  1. 暂无评论