$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>php - How do I programmatically add items of content to a custom post type?|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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...';
}
?>
Post a comment

comment list (0)

  1. No comments so far