Wordpress Insert post create tne meta key and meta value - wordpress

I am creating wp_insert_post to create post from json, while creating post i need to create meta values i have tried both add_post_meta and update_post_meta no results Can anybody help
foreach ( $response->data as $single_data ) {
$post_title = $single_data->name;
$video_id = $single_data->uri;
$thumnbnail_url = $single_data->pictures->sizes[4]->link;
if (!post_exists($post_title)) { // Determine if a post exists based on title, content, and date
$post_id = wp_insert_post(array(
'post_type' => 'vimeo_videos',
'post_title' => $post_title,
'post_status' => 'publish',
));
}
$newPostID = wp_insert_post($post_id);
global $post;
add_post_meta( $post->ID, 'vimeo_video_thumnbnail_url_key', $thumnbnail_url, true );
update_post_meta( $newPostID, 'video_url_id', $video_id );

You're using wp_insert_post twice which does not make sense. The first wp_insert_post is correct and will return the $post_id of the created post upon success. However, your
$newPostID = wp_insert_post($post_id);
is totally wrong and will always store 0 as a result in $newPostID, regardless of whether the post existed beforehand or not since $post_id will never contain a valid post array. What you want is to get the ID of the existing post (which post_exists already returns if successful). Change your code like so:
$existingPostID = post_exists($post_title);
if (!$existingPostID) {
$existingPostID = wp_insert_post(array(
'post_type' => 'vimeo_videos',
'post_title' => $post_title,
'post_status' => 'publish',
));
}
if ($existingPostID) {
update_post_meta( $existingPostID, 'video_url_id', $video_id );
}

For insert new post used this syntax:
add_post_meta( int $post_id, string $meta_key, mixed $meta_value, bool $unique = false )

Related

WordPress XMLRPC - Search Post by Slug and Update

Is there anyway to search posts by slug through XMLRPC
https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.getPosts
getPosts() doesn't seem to return using "name"..
$args = array(
'name' => 'my-slug',
'number' => 1
);
$post = $wpClient->getPosts( $args );
Please let me know if there is a workaround for this, I need to search by slug and then update those slugs remotely via XMLRPC. cheers
I ended up using Methods, this may help someone and save time.. paste the following code in functions.php of the domain you are fetching data from
add_filter('xmlrpc_methods', 'clx_xmlrpc_methods');
function clx_xmlrpc_methods($methods) {
$methods['getPostBySlug'] = 'clx_getpost';
return $methods;
}
function clx_getpost($args) {
global $wp_xmlrpc_server;
$slug = $args["slug"];
$pargs = array(
'name' => $slug,
'post_type' => 'post',
'numberposts' => 1
);
$my_posts = get_posts($pargs);
if( $my_posts ) :
return $my_posts; //echo $my_posts[0]->ID;
endif;
}
from your XMLRPC code use the following to get POST array from slug
$args = array(
'slug' => 'your-post-slug'
);
$postArray = $wpClient->callCustomMethod( 'getPostBySlug', $args );

Check if a slug is existing, else create a new product in woocommerce

I have here a code below that will insert products into the database in woocommerce :
$post = array(
'post_author' => $user_id,
'post_content' => '',
'post_status' => "publish",
'post_title' => $product->part_num,
'post_parent' => '',
'post_type' => "product",
);
$post_id = wp_insert_post( $post, $wp_error );
But, before inserting a new product, I want to check if a slug is existing in the database, else, I want to add a new one and append a number on the slug.
example input:
$new_url = sanitize_title('This Long Title is what My Post or Page might be');
output :
this-long-title-is-what-my-post-or-page-might-be
Now, I want to check if this slug is already existing in the database. If it is existing, I will append a number on the slug(just like what wordpress permalink is doing). If it is already existing, i want to output this as:
this-long-title-is-what-my-post-or-page-might-be-1
I want to add new product into the database together with this new slug.
Does anybody know?
Not tested but just written that code. Try this and let me know
function slug_exists($slug){
if(get_page_by_path( $slug, OBJECT, 'product' )){
return true;
}
return false;
}
$slug = 'your_slug';
$new_slug = $slug;
$c=1;
while(slug_exists($new_slug)){
$new_slug = $slug.'-'.$c;
$c++;
}
// $new_slug containes your desired slug

Why wp_update_post return invalid post id

I am getting an error with WordPress wp_update_post() function that says "Invalid post ID". Here is my code:
$current_item = 273;
$my_post = array(
'ID' => $current_item,
'post_title' => 'This is the post title.',
'post_content' => 'This is the updated content.',
);
$post_id = wp_update_post( $my_post, true );
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
Thanks in advance .
Use 'import_id', not 'ID'.
If there is no post at the ID you specify, wp_update_post() doesn't create a new one - it returns an error. In order to specify the ID of a new post use 'import_id' => $current_item.
Note, though, that if there IS a post with that ID, import_id will cause a new post instead of an update. So if you want to EITHER make a new post with that ID OR update the post at that ID, you'll need an if statement to pick your key:
$newPostKey = (get_post_status($current_item)) ? 'ID' : 'import_id';
// If there's a post with an ID of $current_item, we'll use 'ID'.
// Otherwise, use 'import_id'.
Here's your shiny new code.
$current_item = 273;
$newPostKey = (get_post_status($current_item)) ? 'ID' : 'import_id';
$my_post = array(
$newPostKey => $current_item,
'post_title' => 'This is the post title.',
'post_content' => 'This is the updated content.',
);
$post_id = wp_update_post( $my_post, true );

Creating a page with wp_insert_post()

I have a form that collects data about a user's product and then creates a page in WordPress with
$my_post = array(
'post_content' => "My page content",
'post_title' => $product_title,
'post_name' => $product_title,
'post_type' => 'page', // must be 'page' to accept the 'page_template' below
'page_template' => "listing.php",
'post_status' => "publish"
);
$ID = wp_insert_post( $my_post );
$permalink = get_permalink($ID);
echo "<br />ID for new page is $ID, Permalink for new page is $permalink";
The form data is put into meta variables for the page ID and the listing.php template file pulls it out of there and builds the HTML to display the product page. This all works fine and I can see that the page meta variable, _wp_page_template, gets set correctly to the template file I specified, listing.php:
Now I want to create a second page from the same form data, this one displaying different parts of the data in a different way. So I've added a second block of code, starting at $my_cert below, that creates this second page and specifies a different template, certificate.php, that knows how to build the second version of the data.
$my_post = array(
'post_content' => "My page content",
'post_title' => $product_title,
'post_name' => $product_title,
'post_type' => 'page', // must be 'page' to accept the 'page_template' below
'page_template' => "listing.php",
'post_status' => "publish"
);
$ID = wp_insert_post( $my_post );
$permalink = get_permalink($ID);
echo "<br />ID for new page is $ID, Permalink for new page is $permalink";
$my_cert = array(
'post_content' => "My certificate", // post_content is required
'post_title' => "My certificate", // post_title is required
'post_name' => "My certificate",
'post_type' => 'page', // must be 'page' to accept the 'page_template' below
'page_template' => "certificate.php",
'post_status' => "publish"
);
$CERT_ID = wp_insert_post( $my_cert );
$cert_permalink = get_permalink($CERT_ID);
echo "<br />ID for new certificate is $CERT_ID, Permalink for new certificate is $cert_permalink";
But when I look in the meta data for the second page created, the template is set to "default" instead of certificate.php:
I know I've set up certificate.php correctly as a template (set /* Template Name: certificate */ at the top) because the Page Edit Template dropdown includes certificate:
So does anyone see why I can't create this second page with the template set to certificate.php?
Thanks
Are you sure your page template src for: certificate.php is: certificate.php? And not: templates/certificate.php or something like that. Look in your theme folder and be 100% of the page template path. Check your spelling or for typos in the page template path or name. It must be an exact match.
If you still have problems I would look into and debug the source code of: wp_insert_post()
if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
$post->page_template = $postarr['page_template'];
$page_templates = wp_get_theme()->get_page_templates( $post );
if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
if ( $wp_error ) {
return new WP_Error('invalid_page_template', __('The page template is invalid.'));
}
update_post_meta( $post_ID, '_wp_page_template', 'default' );
} else {
update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
}
}
So its probably this part that fails:
if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) )
Try to modify: wp-includes/post.php and go to the definition of: function wp_insert_post() on row: 2872. And add a new row on row: 3312 for debugging purposes.
echo '<pre>';
print_r( $page_templates );
echo '</pre>';
die();
Make sure your certificate.php is among those in that array. Remember to delete the debug code before continuing. This should give you some answers.

WordPress update_post_meta is returning odd results

Problems with WordPress update_post_meta.
I have a function that should be updating _gravity_form_data. It works, but it is adding extra data for some reason. Here's the function:
Here is the function:
function wpufe_gravity_custom_video( $post_id ) {
if (isset( $_POST['custom_video'])) {
$custom_video = 'a:13:{s:2:"id";s:1:"2";s:13:"display_title";b:0;s:19:"display_description";b:0;s:25:"disable_woocommerce_price";s:2:"no";s:12:"price_before";s:0:"";s:11:"price_after";s:0:"";s:20:"disable_calculations";s:3:"yes";s:22:"disable_label_subtotal";s:2:"no";s:21:"disable_label_options";s:2:"no";s:19:"disable_label_total";s:2:"no";s:14:"label_subtotal";s:8:"Subtotal";s:13:"label_options";s:7:"Options";s:11:"label_total";s:5:"Total";}';
update_post_meta( $post_id, '_gravity_form_data', $custom_video );
}
}
add_action( 'wpuf_add_post_after_insert', 'wpufe_gravity_custom_video' );
add_action( 'wpuf_edit_post_after_update', 'wpufe_gravity_custom_video' );
It SHOULD be making _gravity_form_data have this content:
a:13:{s:2:"id";s:1:"2";s:13:"display_title";b:0;s:19:"display_description";b:0;s:25:"disable_woocommerce_price";s:2:"no";s:12:"price_before";s:0:"";s:11:"price_after";s:0:"";s:20:"disable_calculations";s:3:"yes";s:22:"disable_label_subtotal";s:2:"no";s:21:"disable_label_options";s:2:"no";s:19:"disable_label_total";s:2:"no";s:14:"label_subtotal";s:8:"Subtotal";s:13:"label_options";s:7:"Options";s:11:"label_total";s:5:"Total";}
Yet when it updates the _gravity_form_data field, its output is:
s:429:"a:13:{s:2:"id";s:1:"2";s:13:"display_title";b:0;s:19:"display_description";b:0;s:25:"disable_woocommerce_price";s:2:"no";s:12:"price_before";s:0:"";s:11:"price_after";s:0:"";s:20:"disable_calculations";s:3:"yes";s:22:"disable_label_subtotal";s:2:"no";s:21:"disable_label_options";s:2:"no";s:19:"disable_label_total";s:2:"no";s:14:"label_subtotal";s:8:"Subtotal";s:13:"label_options";s:7:"Options";s:11:"label_total";s:5:"Total";}";
Why is it adding the s:429:" in the beginning and then the extra "; at the end? And most importantly, how do I fix it? :)
Thanks so much!
UPDATE: Was suggested to serialize the data, so I did:
function wpufe_gravity_custom_video( $post_id ) {
if (isset( $_POST['custom_video'])) {
$gubcustom_video = array('id' => 2, 'display_title' => '', 'display_description' => '', 'disable_woocommerce_price' => 'no', 'price_before' => '', 'price_after' => '', 'disable_calculations' => 'yes', 'disable_label_subtotal' => 'no', 'disable_label_option' => 'no', 'disable_label_total' => 'no', 'label_subtotal' => 'Subtotal', 'label_options' => 'Options', 'label_total' => 'Total');
$gubvideodata = serialize($gubcustom_video);
update_post_meta( $post_id, '_gravity_form_data', $gubvideodata );
}
}
add_action( 'wpuf_add_post_after_insert', 'wpufe_gravity_custom_video' );
add_action( 'wpuf_edit_post_after_update', 'wpufe_gravity_custom_video' );
...and still get the incorrect data posted to mysql.
Is there a way to just insert that string I need to insert? That's all I want to do, is update the database with that text.
I can do this in phpMySql easily, just copy and paste the text and it works like a champ. That's the solution I'm hoping for. Thanks again!
It looks like a serialized array that you are trying to insert manually but you should insert it by serializing it using serialize function, for example:
$custom_video = array('id' => 2, 'display_title' => '');
$data = serialize($custom_video);
update_post_meta( $post_id, '_gravity_form_data', $data );
Also, try using following hook:
add_action( 'save_post', 'save_meta_data' );
function save_meta_data($post_id)
{
$custom_video = array('id' => 2, 'display_title' => '');
$data = serialize($custom_video);
update_post_meta( $post_id, '_gravity_form_data', $data );
}
Problem solved. WP User Frontend Pro was setting the meta key with its own value of "1", causing it to re-serialize the serialized string. Problem solved by removing the WPUF meta key and just leaving the field.

Resources