3

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.

  • 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 Aug 28 '14 at 5:14
  • print_r isn't a Drupal function, it's a generic PHP function that comes with standard PHP – Tom J Nowell Nov 12 '14 at 11:54
9

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

  • Great answer, short and sweet. Problem is I don't understand how to get the keys. Note in my code my custom post type 'ait-dir-item.' How do I find out there key names to put where the longitude and latitude place holders are? Is there something like "get_all_key('ait-dir-item') (where the argument is the custom post type)? – user658182 Aug 28 '14 at 5:28
  • You can use get_post_custom( $post_id ) or have a look in the options table. – RRikesh Aug 28 '14 at 5:46
  • @RRikesh cool answer! One thing - the meta keys will be in the wp_postmeta table, not wp_options. See codex.wordpress.org/images/9/97/WP3.8-ERD.png – henrywright Nov 11 '14 at 2:33
  • 1
    Sidenote: to get all meta-values for a post, just use get_post_meta($post->ID);. This will return an array with all meta_keys as keys, and also help you parse what values are available for alteration/outputing – Jimtrim Nov 11 '14 at 10:57
  • 1
    You can also use update_post_meta instead of add_post_meta to crete a new meta key. If the meta key does not already exist, update_post_meta will create it via add_post_meta. add_post_meta is useful if you need to use a unique key. codex.wordpress.org/Function_Reference/update_post_meta – iyrin Nov 17 '14 at 4:53
1

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.

0

Insert and update post programmatically. http://www.pearlbells.co.uk/insert-udpate-wordpress-post-programmatically/

 if( $mydb->num_rows >  0) {

    echo 'Post '.$postCSVContent[0].' exist'.PHP_EOL;
    $template_file = get_post_meta( $postCSVContent[0], '_wp_page_template', true );
    echo 'Template File : '.$template_file.PHP_EOL;

    $updatePost = array(   
        'ID' => $postCSVContent[0],
        'post_title'    => $postCSVContent['1'],
        'post_content'  => $postCSVContent['2'],
        'post_type' => 'doors',
        'post_status'   => 'publish',
        'post_author'   => 1
    );

    wp_update_post( $updatePost );

    update_post_meta( $postCSVContent[0], '_wp_page_template', $template_file );
    updateAcf( $postCSVContent , $postCSVContent[0] );

}
else
{
    echo 'Post '.$postCSVContent[0].' is not existing'.PHP_EOL;        
    echo 'Post parent '.$parentId.PHP_EOL;

    $newIds = wp_insert_post( array(
            'post_title' => $postCSVContent['1'],
            'post_content' => $postCSVContent['2'],
            'post_type' => 'doors',
            'post_status' => 'publish',        
            'post_author'   => 1,
            'post_parent' => $parentId
    ));

    updateAcf( $postCSVContent , $newIds );

Please refer the tutorial that update acf as well. http://www.pearlbells.co.uk/insert-update-acf-image-repeater-field-programmatically/

0
<?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...';
}
?>

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.