Support » Fixing WordPress » Custom Post Types and Custom Fields

  • Hi
    I’m a bit stuck but made some progress but not sure if I’m going about it the right way.

    I’m working on a Dog Rescue website that needs to have dogs for rehoming on the front or home page. Initially, each dog’s details was set up in a post and displayed as they should but when I added other post items they also appeared on the home page.

    I thought about using categories but I don’t think it would work as well. When the dog arrives it should be down as a Rescue or in training, then when the dog has been trained it then needs to be up for rehoming so it’s status needs to change and when it does it should then show on the home page. Once the dog has been successfully been rehomed it’s status needs to change to rehomed and disappear from the home page.

    I’ve used a plugin to set up a custom post type with several custom fields. One of the custom fields is a dropdown that has the options rescue, rehoming & rehomed.

    In my functions.php I have added the custom post type of dog using add_filter as thus

    add_filter( 'pre_get_posts', 'my_get_posts' );
    function my_get_posts( $query ) {
    	if ( is_home() && $query->is_main_query() )
    		$query->set( 'post_type', array( 'post', 'dog' ) );
    	return $query;

    So now the custom post type of dog shows on the home page with all the other posts. This is not what I want, I just want to show dogs for rehoming so now I need to filter out the posts, rescue dogs and rehomed dogs. I was pointed in the direction of meta_query and came up with this:

    [ Moderator note: wrap code in the backtick and not the single quote. ]

    add_action( 'pre_get_posts', 'show_dogs_for_rehoming' );
    function show_dogs_for_rehoming( $query ) {
        if( $query->is_main_query() && is_home() && !is_admin() && is_post_type_archive('dog') ) {
            $args = array(
    	        'post_type' => 'dog',
    	        'meta_query' => array( array('meta_key' => 'dog_status','meta_value' => 'rehoming'))
            $query = new WP_Query( $args );

    Can anyone see where I have gone wrong as I get all posts and all custom post types regardless of the custom field.


Viewing 1 replies (of 1 total)
  • You should put in some debug code to be sure your filter is being run. A quick-and-dirty way is to put in a die("DEBUGGING IN pre_get_posts"); statement.

    I wonder if is_home() and is_post_type_archive(‘dog’) are mutually exclusive. Try taking out is_post_type_archive(‘dog’).

Viewing 1 replies (of 1 total)
  • The topic ‘Custom Post Types and Custom Fields’ is closed to new replies.