User_FTW
User_FTW

Reputation: 524

Check if post name already exists in custom post type category

I have a form that inserts a post into a custom post type with specific taxonomy category, like this:

    $animal_name        = sanitize_text_field($_POST['animal_name']); // Animal name
    $animal_category    = sanitize_text_field($_POST['animal_category']); // Dropdown list of animal categories, ID is passed

    $args = array(
        'post_title'    => $animal_name,
        'post_status'   => 'publish',
        'post_type'     => 'animal'
    );

    $post_id = wp_insert_post( $args );
    wp_set_object_terms( $post_id, intval( $animal_category ), 'species' );

What I can't figure out, is how to check if an animal name already exists in the 'animal' custom post type, in the 'species' taxonomy category (tag).

So as an example, if in the submitted form the $animal_name was 'Golden Retriever', and the $animal_category was 'Dog', the wp_insert_post() should not run if there is already a 'Golden Retriever' in the 'Dog' category.

WordPress already has a post_exists function, but it doesn't seem to cater for a taxonomy.

Upvotes: 1

Views: 517

Answers (1)

mynd
mynd

Reputation: 794

I guess this could be solved by using a WP_Query that has a taxonomy sub-query setup.

$args = [
    'post_title' => 'Golden Retriever',
    'post_type' => 'animal',
    'tax_query' => array(
        array(
            'taxonomy' => 'species',
            'field'    => 'slug'
            'terms'    => 'dog',
        ),
    )
];
//run the query
$query = new WP_Query( $args );

//check post count

if (sizeof($query->posts) === 0) {
    //post not existant so far...
}

Code is untested but it should point you in the right direction.

Upvotes: 1

Related Questions