> For the complete documentation index, see [llms.txt](https://learnphp.gitbook.io/learnphp/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learnphp.gitbook.io/learnphp/wordpress-advand/how-to-set-featured-image-programmatically-post-product-in-wordpress-ok.md).

# 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

```
<?php
/*
Template Name: Add New Product
 */
?>
<?php get_header();?>
<form method="post" enctype="multipart/form-data">
    <p>
      <label>Select Image:</label>
      <input type="file" name="image" required />
    </p>
    <input type="hidden" name="image_nonce" value="<?php echo wp_create_nonce('image_nonce'); ?>" />
    <input type="submit" name="upload_file" value="Submit" />
</form>
<?php
get_footer();?>
```

![](https://1113999984-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M84NwP_L_qEsBHOa2xo%2Fuploads%2FzQy8auJr5AamWEpCKYhO%2FScreenshot_1.png?alt=media\&token=78fd842e-1612-45c2-8deb-ed4f471926a4)

![](https://1113999984-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M84NwP_L_qEsBHOa2xo%2Fuploads%2FJMt33eFHA7ppN3s1YkTb%2FScreenshot_3.png?alt=media\&token=a5149776-e289-4c95-a938-ead7a66cd063)

**Ví dụ 2: Áp dụng với post\_type product**

```
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'     => 'product',
	    );
	    $post_id = wp_insert_post($new_post);
	    wp_update_post(array(
			  'post_title' => 'About',
			  'ID' => $post_id,
			  'meta_input' =>  array(
			    '_regular_price' => '3333',
			    '_price' => 123,
			  ),
			));
      $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

```
<?php
/*
Template Name: Add New Product
 */
?>
<?php get_header();?>
<form method="post" enctype="multipart/form-data">
    <p>
      <label>Select Image:</label>
      <input type="file" name="image" required />
    </p>
    <input type="hidden" name="image_nonce" value="<?php echo wp_create_nonce('image_nonce'); ?>" />
    <input type="submit" name="upload_file" value="Submit" />
</form>
<?php
get_footer();?>
```

![](https://1113999984-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M84NwP_L_qEsBHOa2xo%2Fuploads%2FhGv5r01xZ6lDSAKkOW52%2FScreenshot_4.png?alt=media\&token=51ef4f12-d3bd-4057-9f70-80c59cbad1b8)
