0

Hi I need some help with custom taxonomy and wp_insert_post.

I have a Custom Post Type "Locations" and the custom taxonomy called "poicategory".

My problem is when I insert the post with wp_insert_post the post taxonomy is not created correctly. If I´m watching in Backend post is created but no category is connected to post. When I go in post edit and watch the categories are set to the post (see images).

First image: the created post in Backend -> No categories set -> edit the created post and you see in POI Kategorien 3 selected Categories

Second image: POI Category overview in Backend -> No post in Category.

My first try was this code snipped:

    $ids = array (42,43,44);
    $defaults = array(
    'post_type' => 'locations',
    'post_title' => $postTitle,
    'post_status' => 'draft',
    'comment_status' => 'closed',
    'tax_input' => array(
        'poicategory' => $ids
    ),
    'post_author' => 1,
    'meta_input' => $post_meta,
);
$mh_post_id = wp_insert_post($defaults, true);
if ($mh_post_id != 0 && $mh_post_id != false) {
    set_post_thumbnail($mh_post_id, $_SESSION['mediaDataID'][0]);
    add_post_meta($mh_post_id, '_yoast_wpseo_primary_poicategory', $parentCat);
    destroySession();
}

with this explaned result. So I searched a bit around and found something. So I switch my code to this :

    $ids = array (42,43,44);
    $defaults = array(
    'post_type' => 'locations',
    'post_title' => $postTitle,
    'post_status' => 'draft',
    'comment_status' => 'closed',
    'post_author' => 1,
    'meta_input' => $post_meta,
);


$mh_post_id = wp_insert_post($defaults, true);
if ($mh_post_id != 0 && $mh_post_id != false) {
    set_post_thumbnail($mh_post_id, $_SESSION['mediaDataID'][0]);
    add_post_meta($mh_post_id, '_yoast_wpseo_primary_poicategory', $parentCat);
    wp_set_object_terms($mh_post_id, $ids, 'poicategory', false);
    destroySession();
}

But the result is the same. And now I have no idear whats wrong. I hope someone can help me :).

Post Backend

POICategory Backend

0

Well I found the answer. The code is correct. Wordpress do in taxonomy.php Line 3392

    $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type IN ('" . implode("', '", $object_types ) . "') AND term_taxonomy_id = %d", $term ) );

$count is empty because post_status = 'publish' in WHERE statement and my post are saved as draft.

I think so that´s the reason why the counter are empty on second image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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