0

I read several posts and stack exchange answers but still cannot put the code together to work.

I read the post Query posts by custom fields

I have posts with custom fields, lets say "publisher" with a value "IBM".

I have a page listing all the values for the custom field "publisher".

I want IBM to link to a search result for all the posts with this meta_value.

My index.php page begins with

        <?php while(have_posts()){
        the_post(); ?>

I need to send to index.php the request with meta_key and meta_value, add a filter to the query and list the results, but I don't know how to "stitch" everything so it will do what I want.

Thanks.

1 Answer 1

0

Assuming that this meta is for the post type "post" you could create a loop in two ways, get_posts or WP_Query.
I also prefer the meta_query property over the meta_value and meta_key, because it adds the option to add more meta queries quicker as the array already exists.

The get_posts method

$posts = get_posts([
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => [
        [
            'key'     => 'publisher',
            'value'   => 'IBM',
        ]
    ]
]);

foreach ($posts as $post) {
    // your code here
}

The WP_Query method

$posts = new WP_Query([
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => [
        [
            'key'     => 'publisher',
            'value'   => 'IBM',
        ]
    ]
]);

if ($posts->have_posts()) {
    while ($posts->have_posts()) {
        the_post();

        // your code here
    }
}

The best resource for understanding how this works is the WP_Query documentation

1
  • Thanks! Will try that Jan 3, 2022 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.