How to identify category by Slug when inserting a record with wp_insert_post() from wordpress?

Asked

Viewed 200 times

0

I need to identify categories by Slug when adding a wordpress post.

Common and functional example:

        $post_id = wp_insert_post( array(
            'post_author'   => 1,
            'post_title'    => 'titulo',
            'post_type'     => 'post',
            'post_content'  => 'desc',
            'post_status'   => 'publish',
            'tax_input' => array( 
                  'categoria' => array( 
                    '1'  //categoria identificada por ID
                  ) 
                )
            ) );

How I need you to stay:

        $post_id = wp_insert_post( array(
            'post_author'   => 1,
            'post_title'    => 'titulo',
            'post_type'     => 'post',
            'post_content'  => 'desc',
            'post_status'   => 'publish',
            'tax_input' => array( 
                  'categoria' => array( 
                    'filme'  //categoria identificada por slug
                  ) 
                )
            ) );

Is there such a possibility? The above example didn’t work for me.

1 answer

1


You can use get_term_by() to recover the category ID.

$term = get_term_by( 'slug', 'filme', 'categoria' );
$post_id = wp_insert_post( array(
    'post_author'   => 1,
    'post_title'    => 'titulo',
    'post_type'     => 'post',
    'post_content'  => 'desc',
    'post_status'   => 'publish',
    'tax_input' => array( 
        'categoria' => array( $term->term_id ) 
    )
) );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.