Search code examples
wordpresspluginspostcustom-fieldsskip

Wordpress - Skip posts/pages when a custom field equals something


I'm writing a plugin but I have a problem. When Wordpress is displaying posts & pages on the site, I want it to skip that post/page when the custom field show_post equals 0 (this is a simplified example). How do I do this?

Please remember that this is for a plugin, not a theme, so I can't just edit the theme to skip those posts/pages.


Solution

  • Assuming you want the plugin to work for all themes and all queries.

    You can use something like

    <?php
    add_filter('posts_where', 'check_show_posts');
    function check_show_posts($where) {
        global $wpdb;
        $query = "
            SELECT {$wpdb->prefix}posts.ID as ID
            FROM {$wpdb->prefix}posts
            INNER JOIN {$wpdb->prefix}postmeta m1
              ON ( {$wpdb->prefix}posts.ID = m1.post_id )
            WHERE
            {$wpdb->prefix}posts.post_status = 'publish'
            AND ( {$wpdb->prefix}posts.post_type = 'post' OR {$wpdb->prefix}posts.post_type = 'page' )
            AND ( m1.meta_key = 'show_posts' AND m1.meta_value = '0' )
            GROUP BY {$wpdb->prefix}posts.ID
            DESC;   
            ";
    
            $posts = $wpdb->get_col($query);
            if($posts) {
                $post_list = implode(',', $posts);
                $where .= sprintf(' AND ID NOT IN ( %s )', $post_list);
            }
            return $where;
    }
    

    Update: added if($posts) condition to check if the query returns ID's or not.