WP_INSERT_POST from Form Data, Using WPDB->GetResults - php

I have a series of custom tables which hold distillery operations data on the same MySQL DB as my Wordpress. I would like to use WPDB->GetResults and then WP_INSERT_POST to take form data and create a custom post type from certain distillery table entries. I have an HTML form trying to send a request to a PHP file (code below). I notice that I cannot even see the PHP when opening the webpage. There must be something wrong with this. When debugging the form submission, I am good up until my $.ajax({ call, but I think the .php file is getting me down.
-Newbie doing his best
<!DOCTYPE html>
<html>
<body>
<p>Goofball</p>
<?php
require('header.php');
require('mydomain/test/wp-includes/wp-db.php')
if(isset($_POST['mashId'])){
$mashId = $_REQUEST['mashId'];
new_mash_post($mashId);
}
function new_mash_post($mashId) {
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
$mashes = $wpdb->get_results(
"
SELECT *
FROM mash a
INNER JOIN mashbill b ON a.mashId = b.mashId
INNER JOIN mash_ferm_junc c ON a.mashId = c.mashId
WHERE a.mashId = $mashId
"
);
$oldmashid = 0;
foreach($mashes as $mash){
if($oldmashid != 0){
$oldmashid = $mash->mashId;
$slug = $mash->mashId;
$title = $mash->mashId;
$author_id = 1;
// If the page doesn't already exist, then create it
if( null == get_page_by_title( $title ) ) {
// Set the post ID so that we know the post was created successfully
$post_id = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'your_bottle'
)
);
$json_result = array( 'success' => true, 'post_id' => $post_id);
echo json_encode( $json_result );
// Otherwise, we'll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
echo json_encode("failed");
} // end if
} //end if mashId is new
} //end for loop over selection results
} // end programmatically_create_post
?>
</body>
</html>

Related

How to save radio button values from html form into advanced custom fields?

I am using WordPress to develop a website and I am hitting a roadblock. How do I save the radio button values from an html form into an advanced custom field? The options that I have show up in the admin but the checked option is not picked. I want to change the color of an object according to the value picked. I am also getting the name and a brief description and that stores in the admin database no problem. I am using wp_insert_post() to submit the form because I want to display the results after submitting.
if(isset($_POST['new_post']) == '1') {
$current_post_author_id = get_the_author_meta( 'ID' );
$post_title = wp_strip_all_tags($_POST['postTitle']);
$post_category = $_POST['review'];
$post_content = wp_strip_all_tags($_POST['postContent']);
$postid = get_the_ID();
$postStarOne = $POST['rateOne'];
$postStarTwo = $POST['rateTwo'];
$postStarThree = $POST['rateThree'];
$postStarFour = $POST['rateFour'];
$postStarFive = $POST['rateFive'];
//$custom_meta = get_post_meta($post->ID, 'new_post', true);
$category='review'; // category name for the post
$cat_ID = get_cat_ID( $category ); // need the id of 'review' category
//If it doesn't exist create new 'review' category
if($cat_ID == 0) {
$cat_name = array('review' => $category);
wp_insert_category($cat_name); // add new category
}
//Get ID of category again incase a new one has been created
$new_cat_ID = get_cat_ID($category);
$new_post = array(
'ID' => '',
'post_author' => $user->ID,
'tax_input' => array($category->taxonomy => array($category->review)),
'post_category' => array($new_cat_ID),
'post_content' => $post_content,
'post_title' => $post_title,
'post_value' => $value,
'post_type' => 'review',
'post_status' => 'pending'
);
$post_id = wp_insert_post($new_post);
$field_key_one = 'group_5fb2ace92f979';
$field_key_two = 'group_5fb2bcfd619dd';
$field_key_three = 'group_5fb2be0da827d';
$field_key_four = 'group_5fb2ace92f979';
$field_key_five = 'group_5fb2bf62167a1';
$value_one = $postStarOne;
$value_two = $postStarTwo;
$value_three = $postStarThree;
$value_four = $postStarFour;
$value_five = $postStarFive;
update_field($field_key_one, $value_one, $post_id);
update_field($field_key_two, $value_two, $post_id);
update_field($field_key_three, $value_three, $post_id);
update_field($field_key_four, $value_four, $post_id);
update_field($field_key_five, $value_five, $post_id);
// This will redirect you to the newly created post
//$post = get_post($post_id);
wp_redirect($post_id->guid);
}
?>
This is the code that I am using to bring in the data from the user. The update field is what I thought was supposed to bring in the data from the post into the custom field but I must be using it the wrong way. I'm not worried about the validation yet. When I get it up and running then I can validate. Any help will be appreciated. Thanks in advance

How can I increment CPT title and slug reliably?

I've got a custom post type called 'tasks' with an ACF front end to post each new one.
I'd like to hide the title from the end user, and have the title & slug automatically set & increment.
Task 1, Task 2, Task 3 etc.
I've tried all the code examples on here I can find & nothing seems to be reliable.
Has anyone got anything they've used in the past that works reliably?
Tried this;
add_filter('title_save_pre','auto_generate_post_title');
function auto_generate_post_title($title) {
global $post;
if (isset($post->ID)) {
if (empty($_POST['post_title']) && 'produktionsauftrag' == get_post_type($post->ID)){
// get the current post ID number
$id = get_the_ID();
// add ID number with order strong
$title = 'produktionsauftrag-'.$id;} }
return $title;
}
Just gives me a post with the title 'untitled' & the next post id as the slug
Tried this one
add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
function modify_post_title( $data , $postarr ) {
// Check for the custom post type and it's status
// We only need to modify it when it's going to be published
$posts_status = ['publish', 'future', 'pending', 'private', 'trash'];
if( $data['post_type'] == 'task' && !in_array($data['post_status'], $posts_status)) {
// Count the number of posts to check if the current post is the first one
$count_posts = wp_count_posts('task');
$published_posts = $count_posts->publish;
// Check if it's the first one
if ($published_posts == 0) {
// Save the title and the slug
$data['post_title'] = date('Y-m') . '-1';
$data['post_name'] = sanitize_title($data['post_title']);
} else {
// Get the most recent post
$args = array(
'numberposts' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'task',
'post_status' => 'publish'
);
$last_post = wp_get_recent_posts($args);
// Get the title
$last_post_title = $last_post['0']['post_title'];
// Get the title and get the number from it.
// We increment from that number
$number = explode('-', $last_post_title);
$number = intval($number[2]) + 1;
// Save the title and the slug
$data['post_title'] = date('Y-m') . '-' . $number;
$data['post_name'] = sanitize_title($data['post_title']);
}
}
return $data;
}
Does nothing, acf form page just refreshes itself

wordpress, inserting values into custom post type not working

When processing the form i want the values to be inserted into the custom post type products.
Here is what i have done so far
$art_title = $_POST['art_title'];
$i = 0;
foreach($art_title as $value) {
$art_title = $_POST['art_title'][$i];
$art_width = $_POST['art_width'][$i];
$art_height = $_POST['art_height'][$i];
$art_price = $_POST['art_price'][$i];
$art_creation_date = $_POST['art_creation_date'][$i];
$art_upload = $_FILE['art_upload'][$i];
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $art_title,
'post_status' => 'draft',
'post_type' => 'products'
);
//save the new post
$pid = wp_insert_post($new_post);
$attachment_id = media_handle_upload( 'art_upload', $pid );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
$i++;
}
I used media_handle_upload along with the post id but this isn't working.
What i want to know is how do i insert these $_POST values into the custom post type products along with the image as product_image?
The custom post type is the woocommerce products.
Any help greatly appreciated. An example would be great.
please replace this line
$art_upload = $_FILE['art_upload'][$i];
to
$art_upload = $_FILES['art_upload'][$i];

Wordpress csv import duplicate

I've used an adapted version of a csv import plugin for wordpress. It imports the csv to create and update posts. To update existing posts I've added an edit that finds the post id by title, then if it exists it overwrites, otherwise it creates a new post.
Problem is that it seems to not be very reliable! If I import the same csv several times it over-writes most of them but I get a few duplicates. Is there any way I can make this more reliable, or is there another way I can deal with duplicate posts?
main function for creating posts here
function create_post($data, $options) {
extract($options);
//edit 1 added here
global $wpdb;
//end
$data = array_merge($this->defaults, $data);
$type = $data['csv_post_type'] ? $data['csv_post_type'] : 'post';
$valid_type = (function_exists('post_type_exists') &&
post_type_exists($type)) || in_array($type, array('post', 'page'));
if (!$valid_type) {
$this->log['error']["type-{$type}"] = sprintf(
'Unknown post type "%s".', $type);
}
$new_post = array(
'post_title' => convert_chars($data['csv_post_title']),
'post_content' => wpautop(convert_chars($data['csv_post_post'])),
'post_status' => $opt_draft,
'post_type' => $type,
'post_date' => $this->parse_date($data['csv_post_date']),
'post_excerpt' => convert_chars($data['csv_post_excerpt']),
'post_name' => $data['csv_post_slug'],
'post_author' => $this->get_auth_id($data['csv_post_author']),
'tax_input' => $this->get_taxonomies($data),
'post_parent' => $data['csv_post_parent'],
);
// edit 2 here
$new_post['ID'] = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $data['csv_post_title'] . "'" );
// ends
// pages don't have tags or categories
if ('page' !== $type) {
$new_post['tags_input'] = $data['csv_post_tags'];
// Setup categories before inserting
$cats = $this->create_or_get_categories($data, $opt_cat);
$new_post['post_category'] = $cats['post'];
}
// edit 3
if(!empty($new_post['ID'])) {
$id = wp_update_post($new_post);
} else {
$id = wp_insert_post($new_post);
}
// ends
if ('page' !== $type && !$id) {
// cleanup new categories on failure
foreach ($cats['cleanup'] as $c) {
wp_delete_term($c, 'category');
}
}
return $id;
}
thanks
Fixed! I used the built in wordpress function, get_page_by_title . Here is the code I used to target the correct post.
if (!get_page_by_title( $bpp_title, 'OBJECT', 'publications')) {
$id = wp_insert_post($new_post);
} else {
$bpp_page = get_page_by_title( $bpp_title, 'OBJECT', 'publications');
$new_post['ID'] = $bpp_page->ID;
$id = wp_update_post($new_post);
}

Auto Increment Custom Post Type Title

I created a custom post type "Testimonials" and removed support for the title. I am wanting to auto increment the title such as Testimony #1, Testimony #2, Testimony #3, etc.. right now it saves as "auto draft". Any help would be appreciated.
BTW I am not echoing the title, it will only be visible by me.
Made some improvements to the code provided #the-alpha.
// Use a filter to make the change
add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
function modify_post_title( $data , $postarr ) {
// Check for the custom post type and if it's in trash
// We only need to modify if it when it's going to be published
$posts_status = ['publish', 'future', 'draft', 'pending', 'private', 'trash'];
if( $data['post_type'] == 'oferta' && !in_array($data['post_status'], $posts_status)) {
// Count the number of posts to check if the current post is the first one
$count_posts = wp_count_posts('you custom post type');
$published_posts = $count_posts->publish;
// Check if it's the first one
if ($published_posts == 0) {
$data['post_title'] = date('Y-m') . '-1';
} else {
// Get the most recent post
$args = array(
'numberposts' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'you custom post type',
'post_status' => 'publish'
);
$last_post = wp_get_recent_posts($args);
// Get the title
$last_post_title = $last_post['0']['post_title'];
// Get the title and get the number from it.
// We increment from that number
$number = explode('-', $last_post_title);
$number = $number[2] + 1;
// Save the title.
$data['post_title'] = date('Y-m') . '-' . $number;
}
}
return $data;
}
In this case the user doesn't have the ability to modify the custom post type title and whole thing increments based on the title.
on post submission from frontend custom post title set to #1 but not increment to #2 on second post submission..
This is the exact code used in functions.php
add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
function modify_post_title( $data , $postarr )
{
if( $data['post_type'] == 'your custom post type' ) {
$last_post = wp_get_recent_posts( '1');
$last__post_id = (int)$last_post['0']['ID'];
$data['post_title'] = 'Testimony #' . ($last__post_id+1);
}
return $data;
}

Categories