How to identify category by slug when inserting a record with wp_insert_post () of wordpress?

0

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

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 do I need it 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 a possibility? The above example did not work for me.

    
asked by anonymous 31.03.2015 / 01:52

1 answer

1

You can use get_term_by () to retrieve 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 ) 
    )
) );
    
02.04.2015 / 16:23