I created plugin for get post title via API on submit. I used simple api request for getting data after via wp_insert_post() function add to DB. But i want check every time on submit to exists title. If there is a new post title then add to the database if not then it will report that 'There are no new posts'
plugin.php
if(isset($_POST['enable'])) {
$url='api/url';
$result = file_get_contents($url);
$resultData = json_decode($result);
foreach ($resultData as $job) {
$post_exists = get_page_by_title( $job->JobTitle, OBJECT, 'post');
if ( post_exists) {
$data = array (
'post_type' => 'post',
'post_title' => $job->JobTitle,
'post_status' => 'publish',
'post_author' => $user_ID
);
$post_id = wp_insert_post( $data );
}
}
echo "Done!";
}
Try this code.
if( isset( $_POST['enable'] ) ) {
$url = 'api/url';
$result = file_get_contents( $url );
$resultData = json_decode( $result );
foreach ($resultData as $job) {
$post_title = sanitize_title( $job->JobTitle );
$post_id = post_exists( $post_title );
if( !$post_id ){
$data = array(
'post_type' => 'post',
'post_title' => $post_title,
'post_status' => 'publish',
'post_author' => $user_ID,
);
$post_id = wp_insert_post( $data );
}else{
//post title exist
}
}
}
You should try this,
This code will return an array of all posts that match the title.
global $wpdb;
$query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title = "'.$post_title.'" AND post_status="publish"');
$post_exists = $wpdb->get_results( $query );
Related
I have created a site whereby athletes can register and create their own templated profile page. On registration, I automatically create a custom post (their profile) and set the user as the author of that post.
However, I cannot for the life of me set the post title as the user's (now author's) first name and surname. For instance, if John Smith registers, I would like the post title to read John Smith, and the slug to convert to athlete/john.smith.
I have used $user_info->nickname for now, but this causes both the title and the slug to read as john.smith
This is the code I am using -any pointers would be greatly appreciated:
add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
if ($this_user_role == 'author') {
// Create a new post
$user_post = array(
'post_title' => $user_info->nickname,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_info->ID
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
You should also use post_name for slug(john.smith) and first_name,last name for post title like this:
add_action( 'user_register', 'wpse_216921_company_cpt', 20, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
if ($this_user_role == 'author') {
$post_title = $user_info->first_name.' '.$user_info->last_name;
$post_title = trim(ucwords($post_title));
$post_slug = preg_replace('/\s+/', '.', $post_title);
// Create a new post
$user_post = array(
'post_title' => $post_title, //$user_info->display_name,
'post_name' => $post_slug,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_info->ID
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
You can use firstname and lastname like below:
add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
$first_name = $user_info->first_name;
$last_name = $user_info->last_name;
if ($this_user_role == 'author') {
// Create a new post
$user_post = array(
'post_title' => $first_name . ' ' . $last_name,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_info->ID
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
Not tested but it should works.
Thanks for the assistance guys. It turned out to be an Ultimate Member issue, and I needed to use the UM Hook um_registration_complete.
The final solution that worked is as follows:
//Create Custom Post Type on registration
add_action( 'um_registration_complete', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
if ($this_user_role == 'author') {
$post_title = $user_info->first_name.' '.$user_info->last_name;
$post_title = trim(ucwords($post_title));
$post_slug = preg_replace('/\s+/', '.', $post_title);
// Create a new post
$user_post = array(
'post_title' => $post_title, //$user_info->display_name,
'post_name' => $post_slug,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_info->ID
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
How I can get specific post data in foreach loop? (only title for example)
Here is my PHP (returns all post data):
function myspace_get_posts_by_tag(WP_REST_Request $request) {
$slug = $request['slug'];
$page = $request['page'];
$term = get_term_by('slug', $slug, 'post_tag');
$posts_per_page = 1;
$args = array(
'tag__in' => $term->term_id,
'posts_per_page' => $posts_per_page,
'paged' => $page,
'orderby' => 'date',
'order' => 'desc',
);
$query = new WP_Query( $args );
$max_pages = $query->max_num_pages;
$total = $query->found_posts;
$posts = $query->posts;
$controller = new WP_REST_Posts_Controller('post');
foreach ( $posts as $post ) {
$response = $controller->prepare_item_for_response( $post, $request );
$data[] = $controller->prepare_response_for_collection( $response );
}
$response = new WP_REST_Response($data, 200);
$response->header( 'X-WP-Total', $total );
$response->header( 'X-WP-TotalPages', $max_pages );
return $response;
}
I cut down some code just for the sake of example.
You are using WP_Query() to fetch the posts later in the foreach loop.
In that case, $post is a WP_Post Object. So you can access its properties, in your case - the post's title:
$post->post_title
I have a custom post called "project", and it has an acf field called "ponum".
When a customer purchases a product, I'd like to add the customer's order number to the "ponum" field of the user’s post in the custom post "project".
Getting an order number & creating a post works, but I have no idea how to add this number to the acf field on a thank you page.
add_action( 'woocommerce_thankyou', 'create_post_on_order' );
function create_post_on_order($order_id)
{
global $wpdb;
//print('<pre>'.print_r( $wpdb, true ).'</pre>');
$order = wc_get_order($order_id);
if (!$order->get_id()) {
return;
}
$current_user = wp_get_current_user();
$current_user_id = $current_user->display_name;
$post_title = $order_id . ' - ' . $current_user_id;
// Check post already exit with our title or not
$query = $wpdb->prepare(
'SELECT ID FROM ' . $wpdb->posts . '
WHERE post_title = %s
AND post_type = \'project\'',
$post_title
);
$wpdb->query($query);
if (!$wpdb->num_rows) {
$post_id = wp_insert_post(
array(
'author' => $current_user_id,
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'project'
)
);
}
}
Would you please help me?
Thank you.
Once you have the value for your acf (i.e "$order_id"), then you could use the following code to update the acf field:
UPDATED ANSWER BASED ON YOUR NEW CODE
add_action('woocommerce_thankyou', 'create_post_on_order');
function create_post_on_order($order_id)
{
$order = wc_get_order($order_id);
if (!$order->get_id()) {
return;
}
$current_user = get_userdata(get_current_user_id());
$current_user_name = $current_user->display_name;
$post_title = $order_id . ' - ' . $current_user_name;
$query = new WP_Query(array(
"author" => get_current_user_id(),
"post_type" => "project",
"title" => $post_title
));
if ($query->found_posts == 0) {
$post_id = wp_insert_post(
array(
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'project',
"meta_input" => array(
"ponum" => $order_id
)
)
);
// It should work without this, this is just a double check!
if (get_post_type($post_id) == "project") {
$ponum_key = 'ponum';
$ponum_field_value = get_field($ponum_key);
if (empty($ponum_field_value)) {
$ponum_field_value = $order_id;
update_field($ponum_key, $ponum_field_value);
}
}
}
}
Hi i am trying to insert data to wordpress table its successfully added but it duplicates data each time page refreshed, i want to insert data if the is new otherwise do nothing
foreach ( $response->data as $single_data ) {
// post title
$post_title = $single_data->name;
global $wpdb;
//tablename
$tablename = $wpdb->prefix . "posts";
$wpdb->insert($tablename,
array(
'post_type' => 'vimeo_videos',
'post_title' => $post_title,
'post_status' => 'publish',
),
array('%s', '%s', '%s')
);
}
Please try this. I created an array and tried this. Successfully inserted data into database. Please make it as you got your array. I hope it will be helpful for you
$response = array("title"=>array("title one",'title two'));
//echo "<pre>";print_r($response);echo "</pre>";exit();
foreach ( $response['title'] as $single_data ) {
$post_title = $single_data;
global $wpdb;
$allPosts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_title LIKE '%s'", '%'. $wpdb->esc_like( $post_title ) .'%') );
//echo "<pre>";print_r($allPosts);echo "</pre>";exit();
if (count($allPosts) == 0) {
$tablename = $wpdb->prefix . "posts";
$wpdb->insert($tablename,
array(
'post_type' => 'vimeo_videos',
'post_title' => $post_title,
'post_status' => 'publish',
),
array('%s', '%s', '%s')
);
} else {
/*Do whatever you like */
}
}
Thank you all for your response
I have found solution like this and it works fine
foreach ( $response->data as $single_data ) {
$post_title = $single_data->name;
if (!post_exists($post_title)) { // Determine if a post exists based on title, content, and date
$post_id = array(
'post_type' => 'vimeo_videos',
'post_title' => $post_title,
'post_status' => 'publish',
);
}
$newPostID = wp_insert_post($post_id);
}
Here is the code I am using. It creates duplicate post every time I refresh. Also, how can I add custom field to my post?
My array looks like this:
[{
"featured":"",
"exclusive":"",
"promo_id":"XXX",
"offer_id":"1",
"title" : "Super Cars"
}]
My php code:
<?php
$json = "url";
$response = file_get_contents($json);
$mydecode = json_decode($response);
for ($i = 10; $i < 15; $i++) {
$title = str_replace("&", "&", $mydecode[$i]->title);
$id = $mydecode[$i]->offer_id;
$link = $mydecode[$i]->link;
if( $id === "x" ) {
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'coupon'
);
$post_id = wp_insert_post($new_post);
}
}
?>
The code successfully inserts posts but duplicate every time I refresh.
If anyone can contribute a bit, it would be great!
Update your code to following,
<?php
$json = "http://tools.vcommission.com/api/coupons.php?apikey=xxxxxxxxxx";
$response = file_get_contents($json);
$mydecode = json_decode($response);
for ($i = 0; $i < 15; $i++) {
$title = str_replace("&", "&", $mydecode[$i]->coupon_title);
$description = str_replace("&", "&", $mydecode[$i]->coupon_description);
$store_name = $mydecode[$i]->offer_name;
$coupon_type = $mydecode[$i]->coupon_type;
$coupon_code = $mydecode[$i]->coupon_code;
$link = $mydecode[$i]->link;
$expiry_date = $mydecode[$i]->coupon_expiry;
if( $coupon_type === "Coupon" ) {
// Check if already exists
$get_page = get_page_by_title( $title );
if ($get_page == NULL){
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'coupon'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $post_id, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $get_page->ID, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}
?>
I hope this helps.