0

I am using the following code to show my custom post types on my front page along with the default post type:

// allows the products to show up on the main page
function add_custom_post_type_to_query( $query ) {
    if ( ! is_admin()  &&  $query->is_main_query() ) {
       if ( $query->is_date() ||  $query->is_home()  ) {

           $query->set( 'post_type', array('post', 'product') );

       }
    }
}
add_action( 'pre_get_posts', 'add_custom_post_type_to_query' );

How would I modify this code to only show/add custom post types of product where the custom field called show_on_front_page which is a boolean (ACF checkbox) is set to true (checked)?

0

1 Answer 1

1

I believe that if all your products have the custom meta field show_on_front_page with some containing '1' and some containing '0' or some such, AND your regular posts do not have that field, then something like below should work:

//...
$query->set('post_type', array('post', 'product'));
//add this
        $meta_key = 'show_on_front_page';
        $query->set('meta_query',
                array(
                    'relation' => 'OR',
                    array(
                        'key' => $meta_key,
                        'value' => '1',
                        'compare' => '='
                    ),
                    array(
                        'key' => $meta_key,
                        'compare' => 'NOT EXISTS'
                    )
                )
        );
//...

Caveat: If some of the products don't have the meta field set to anything they will show as well.

See https://developer.wordpress.org/reference/classes/wp_meta_query/

1
  • Thank you! That worked perfectly!
    – timbram
    Jul 10, 2022 at 19:29

Your Answer

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

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