How to query posts with custom fields in WordPress
Below screenshot shows a post with a custom field of Notes …
Suppose we want to query all posts that contains this custom field “Notes”. In this tutorial, we will show you how to run this query in a custom template page.
1. First setup a custom template page as described in our previous tutorial. We are using the Twenty Fourteen theme. In this theme, we duplicated page.php and called it “list-notes.php”. Add the “Template Name: List Notes Page” in the comment section as shown…
2. Now we can create a new page and set its template to “List Notes Page”. We also set its visibility to “private” so that only admins logged into the WordPress dashboard can see this page.
3. Before we can construct a query to find all posts with “Notes”, we have to understand how the custom fields are stored in the database. It is good to have a database browser such as phpMyAdmin to browse the database. The custom fields are stored in the postmeta table. Query this table for meta_key = “Notes” and you can retrieve the fields post_id and meta_value. The post_id field links to the ID field in posts table. Now we can also get the post_title and guid from the posts table. This will enable us to print out the post title that links to the post permalink (via the guid).
The query that we put after the loop in list-posts.php is …
Remember to use “$wpdb->posts” to get the table name for the posts table. This will give you the table name with the correct database prefix attached. After we have retrieved our results into the array $posts_with_notes, we use the foreach loop to iterate through the array constructing the link to posts with notes as well as displaying the Notes value.
Our results looks like …