Query custom post type by custom field

You got it pretty close. Here’s a working example of what you’re trying to do:

class Wpse_126374 {

    public function __construct() {
        add_action( 'init', array( $this, 'rewrites' ) );
        add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ) );
    }

    public function rewrites() {
        add_rewrite_tag( '%parent_id%', '(\d+)' );
    }

    public function pre_get_posts( $query ) {
        // Don't run this on admin pages or secondary queries
        if ( is_admin() || ! $query->is_main_query() || $query->is_archive() )
            return;

        if ( '' != ( $parent_id = get_query_var( 'parent_id' ) ) ) {
            $query->set( 'meta_key', '_wpcf_belongs_artist_id' );
            $query->set( 'meta_value', $parent_id );
        }
    }

}
$wpse_126374 = new Wpse_126374;

This should allow you to have parent_id=24 in the URL.

Leave a Comment