👉How to Set Featured Image Programmatically post, product in WordPress (ok)

https://artisansweb.net/set-featured-image-programmatically-wordpress/

Ví dụ 1: Áp dụng với post_type post

C:\xampp\htdocs\style2\wp-content\themes\twentytwentyone\functions.php

function fn_set_featured_image() {
  if (isset($_POST['upload_file']) && wp_verify_nonce($_REQUEST['image_nonce'], 'image_nonce')) {
    $upload = wp_upload_bits($_FILES["image"]["name"], null, file_get_contents($_FILES["image"]["tmp_name"]));
    if (!$upload['error']) {
      $new_post = array(
	        'post_title'    => 'title',
	        'post_content'  => 'content',
	        'post_status'   => 'pending',
	        'post_type'     => 'post',
	    );
	    $post_id = wp_insert_post($new_post);
      $filename    = $upload['file'];
      $wp_filetype = wp_check_filetype($filename, null);
      $attachment  = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => sanitize_file_name($filename),
        'post_content'   => 'lioneltest',
        'post_status'    => 'inherit',
      );
      $attachment_id = wp_insert_attachment($attachment, $filename, $post_id);
      if (!is_wp_error($attachment_id)) {
        require_once ABSPATH . 'wp-admin/includes/image.php';
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        set_post_thumbnail($post_id, $attachment_id);
      }
    }
  }
}
add_action('init', 'fn_set_featured_image');

C:\xampp\htdocs\style2\wp-content\themes\twentytwentyone\create-new-product.php

Ví dụ 2: Áp dụng với post_type product

C:\xampp\htdocs\style2\wp-content\themes\twentytwentyone\create-new-product.php

Last updated

Was this helpful?