0

When creating a post programmatically (with wp_insert_post();), how do you select the format?

  • Can you be more specific in what you mean by "format"? The post_type? – jasonp Sep 12 at 18:20
  • 1
    If enabled by themes, WordPress supports post formats: image, aside, quote, video, etc.. – Matthew Brown aka Lord Matt Sep 12 at 18:22
  • 1
    I've never worked with post formats before, but this may point you in the right direction: developer.wordpress.org/reference/functions/set_post_format. If nothing else, you should be able to create a post, and then use set_post_format() after that. Probably not the most efficient way though. – jasonp Sep 12 at 18:28
1

As post_format is a custom taxonomy and the different formats terms, you should be able to use the tax_input parameter in the new post args array to set the format. Something along these lines,

$new_post_args = array();

// e.g. $format_slug = 'gallery';
$valid_formats = get_post_format_slugs();
if ( 'standard' !== $format_slug && in_array( $format_slug, $valid_formats ) ) {
  $new_post_args['tax_input']['post_format'] = 'post-format-' . $format_slug;
}

wp_insert_post( $new_post_args );
1
$post_id  = wp_insert_post( $args );
$tag = 'post-format-test';
$taxonomy = 'post_format';
wp_set_post_terms( $post_id, $tag, $taxonomy );
  • That's certainly an interesting hack. It doesn't entirely surprise me that formats are stored as an internal taxonomy. I think I'll stick with set_post_format() as suggested in comments. – Matthew Brown aka Lord Matt Sep 13 at 7:19

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.