Created
August 2, 2016 09:11
-
-
Save morgyface/66b8cdeb494bebb686920daad16826bd to your computer and use it in GitHub Desktop.
WordPress | Get posts that do NOT have a custom field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| global $post; | |
| $args = array( | |
| 'posts_per_page' => 15, | |
| 'post_type' => 'post', | |
| 'meta_query' => array( | |
| array( | |
| 'key' => 'feature', | |
| 'value' => 0 | |
| ) | |
| ) | |
| ); | |
| $myposts = get_posts( $args ); | |
| if ( $myposts ) { | |
| echo '<ul>' . PHP_EOL; | |
| foreach($myposts as $post) : | |
| setup_postdata($post); | |
| $title = get_the_title(); | |
| $link = get_the_permalink(); | |
| echo '<li>'; | |
| echo '<a href="' . $link . '" title="' . $title . '" rel="bookmark">' . $title . '</a>'; | |
| echo '</li>' . PHP_EOL; | |
| endforeach; | |
| wp_reset_query(); | |
| echo '</ul>' . PHP_EOL; | |
| } | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Get Posts that do NOT have a custom field.
This is useful in situations where you provide an ACF option to highlight posts. In this instance we are checking for posts that have check box option of featured. We would first run the featured get_posts query and then, following it, run the example above, which would exclude the featured items that have already been displayed in the previous query.
Do consider this though; if you add the featured custom field after creating the post, it will not have a zero value. It will simply not exist or be null. You could, of course, use meta_query and "NOT EXIST" to identify the posts but this becomes problematic when posts are updated and then suddenly gain the zero value. The solution is, make sure you create the field before creating your posts or, alternatively, re-publish your posts after adding the field.