php - How do I programmatically add items of content to a custom post type?

admin2025-06-06  8

I have a custom post type to which I'd like to programmatically import data. I have followed these instructions and these, and I can easily do it for WP typical pages and posts.

However, my custom post type has custom fields for, for example, longitude and latitude. How do I figure how how those names (array keys) should be referred to in the post array?

$defaults = array(
            'comment_status' => 'closed',
            'ping_status' => 'closed',
            'post_author' => $author_id,
            'post_name' => $slug,
            'post_title' => $title,
            'post_status' => 'publish',
            'post_type' => 'custom-post-type',
       longitude => $my_long,   // <- what's the key here?
       latitude  => $my_lat     // <- what's the key here?
            );

$images = array_of_images; // <- how do these get added?

There are about 40 extra fields I have to add data to.

Additionally, each of my items of content has image attachments, and I want to programmatically add those as well (either from a URL or from my local hard drive, whichever approach is best).

As an answer, I'm looking for a very simple, but fully functioning script (or at least fully complete pseudo code) that would take into account all the programmatic steps I need to take to get a post into the database with it's related image attachments. The result should be the same as if I filled out all the fields, uploaded media, and hit "Publish" from within Wordpress.

I have a custom post type to which I'd like to programmatically import data. I have followed these instructions and these, and I can easily do it for WP typical pages and posts.

However, my custom post type has custom fields for, for example, longitude and latitude. How do I figure how how those names (array keys) should be referred to in the post array?

$defaults = array(
            'comment_status' => 'closed',
            'ping_status' => 'closed',
            'post_author' => $author_id,
            'post_name' => $slug,
            'post_title' => $title,
            'post_status' => 'publish',
            'post_type' => 'custom-post-type',
       longitude => $my_long,   // <- what's the key here?
       latitude  => $my_lat     // <- what's the key here?
            );

$images = array_of_images; // <- how do these get added?

There are about 40 extra fields I have to add data to.

Additionally, each of my items of content has image attachments, and I want to programmatically add those as well (either from a URL or from my local hard drive, whichever approach is best).

As an answer, I'm looking for a very simple, but fully functioning script (or at least fully complete pseudo code) that would take into account all the programmatic steps I need to take to get a post into the database with it's related image attachments. The result should be the same as if I filled out all the fields, uploaded media, and hit "Publish" from within Wordpress.

Share Improve this question edited Nov 11, 2014 at 0:19 user658182 asked Aug 28, 2014 at 5:12 user658182user658182 6252 gold badges14 silver badges35 bronze badges 2
  • side note, I come from a Drupal background where I'd use PRINT_R( $post_array ). I'm looking for something like that, although I'm sure there is a Wordpress way of doing things. – user658182 Commented Aug 28, 2014 at 5:14
  • print_r isn't a Drupal function, it's a generic PHP function that comes with standard PHP – Tom J Nowell Commented Nov 12, 2014 at 11:54
Add a comment  | 

3 Answers 3

Reset to default 12

You should first run the wp_insert_post() which will return the post ID. Then use that post ID to add your custom fields. Use add_post_meta() to add the custom fields.

$post_id = wp_insert_post( $args );

add_post_meta( $post_id, 'longitude', $my_long );
add_post_meta( $post_id, 'latitude', $my_lat );

For image attachments, you can refer to this question: How to set featured image to custom post from outside programmatically

Completely untested but I just threw this together:

$post_data = array (
    'comment_status'    => 'closed',
    'ping_status'       => 'closed',
    'post_author'       => $author_id,
    'post_name'         => $slug,
    'post_title'        => $title,
    'post_status'       => 'publish',
    'post_type'         => 'custom-post-type', 
);

$post_ID = wp_insert_post( $post_data );

if ( ! is_wp_error( $post_ID ) ) {

    $post_meta = get_post_meta( $post_ID );

    if ( $post_meta ) {

        foreach ( $post_meta as $key => $value ) {

            if ( preg_match('/(\.jpg|\.png)$/', $value ) {

                $file = file_get_contents( $value );

                $tmpfname = tempnam( '/tmp',  'img' );

                $handle = fopen( $tmpfname );

                fwrite( $handle, $file );

                if ( getimagesize( $tmpfname ) ) {

                    $image_url  = $value;
                    $upload_dir = wp_upload_dir();
                    $image_data = file_get_contents( $image_url );

                    $filename   = end( explode( '/', $image_url ) );
                    $fileName   = end( explode( '/', $filename ) );

                    $uploadDir  = end( explode( 'uploads', $imageUrl ) );
                    $uploadDir  = str_replace( $fileName, '', $uploadDir );

                    $filename   = $fileName;

                    if ( wp_mkdir_p( $upload_dir['path'] ) ) {

                        $file = $upload_dir['basedir'] . $uploadDir . $filename;

                    } else {

                        $file = $upload_dir['basedir'] . $uploadDir . $filename;
                    }

                    file_put_contents( $file, $image_data );

                    $wp_filetype = wp_check_filetype( $filename, null );

                    $attachment = array (
                        'post_mime_type'    => $wp_filetype['type'], 
                        'post_title'        => sanitize_file_name( $filename ), 
                        'post_content'      => '', 
                        'post_status'       => 'inherit',
                    );

                    $attach_id = wp_insert_attachment( $attachment, $file, $post_ID );

                    // Include image.php
                    require_once(ABSPATH . 'wp-admin/includes/image.php');

                    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

                    wp_update_attachment_metadata( $attach_id, $attach_data );

                }

                fclose( $handle );

            } else {

                add_post_meta( $post_ID, $key, $value );

            }

        }

    }

}

The code should be self-documenting, but feel free to ask if you've got any questions or if it doesn't work.

<?php
require_once 'wp-load.php'; //path of wp-load.php

$name = 'my post';
$content = 'dummy Content here';
$featured_image = 'fullimage url.jpg'; //pass here full image url

$post_data = array(
    'post_title'    => wp_strip_all_tags( $name ),
    'post_content'  => $content,
    'post_status'   => 'publish',
    'post_type'     => 'post',
    'post_author'   => 1,
    'post_category' => array(1,2),
    'page_template' => ''
);
$post_id = wp_insert_post( $post_data, $error_obj );

// for custom field
//add_post_meta( $post_id, 'post_date', 'Dec 5, 2018' ); // second parameter is your custom field name, 3rd parameter is value

generate_Featured_Image($featured_image, $post_id );

function generate_Featured_Image( $image_url, $post_id  ){
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    if(wp_mkdir_p($upload_dir['path']))
        $file = $upload_dir['path'] . '/' . $filename;
    else
        $file = $upload_dir['basedir'] . '/' . $filename;
    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
    $res2= set_post_thumbnail( $post_id, $attach_id );
    echo 'post created...';
}
?>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749176355a317001.html

最新回复(0)