Duplication of message when adding to DB in wordpress - php

When i try to add one post to db using wp_insert_post() in db added two posts:
Ajax request:
/wp-admin/admin-ajax.php?action=getchats&chat_type=all-chat&last_msg=110&add_msg=true&chat_message=helloworlds
action for this:
add_action( 'wp_ajax_getchats', 'getchats');
function getchats(){
if (!isset($_GET['last_msg'])||(!is_numeric($_GET['last_msg'])||(!isset($_GET['chat_type'])))){
die(json_encode(array('error' => 'no_latest')));
}
$cat_id = get_cat_ID($_GET['chat_type']); //the categories name
if ((isset($_GET['add_msg']))&&(isset($_GET['chat_message']))){
$user_id = get_current_user_id();
$description = $_GET['chat_message'];
$title = $description;
if (strlen($title)>20){
$title = mb_substr($title, 0, 20, 'UTF-8');
}
$my_post = array(
'post_content' => $description,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'chatmsg',
'post_author' => $user_id,
'post_category' => array($cat_id)
);
wp_insert_post($my_post);
}
$args=array(
'numberposts' => 3,
'orderby' => 'ID',
'category' => $cat_id,
'post_type' => 'chatmsg',
'post_status' => 'publish',
);
$messages = [];
$posts = get_posts($args);
die(json_encode($posts));
foreach( $posts as $post ){
if ($post->ID > $_GET['last_msg']){
$row = array(
'id' => $post->ID,
'message'=>$post->post_content,
'author'=>$post->post_author,
'date'=>$post->post_date,
);
$message[] = $row;
}
}
die(json_encode(array('error' => 'ok', 'messages'=> $messages)));
}
Why am i using only one wp_insert_post but receive two post?
UPD: Need use wp_doing_ajax for it. Thanks for answer Maxim Sarandi.
if( wp_doing_ajax() ) {
add_action('wp_ajax_getchats', 'getchats');
function getchats()
{
//some code
}
}

Maybe this or this might help you.
And can i give you a few recommendation to your code style?
First - use $_POST for similar queries.
Second - stop use die(wp_send_json()). Inside wp_send_json already present die(); Just use wp_send_json_error() for error response or wp_send_json_success(); or wp_send_json()
Third - use nonces and check_ajax_referer();
Fourth - stop cloning not needed brackets.

Related

Custom Post Type Get Url Loop ShortCode

I have a PHP script here I can't seem to wrap my head around, im basically trying to create a shortcode that displays the next custom post type url, then when the current post is also the last post, it loops back pulling the url to the first post.
everything works except for when you are on the final post, the shortcode displays the ID of the current post (final post) instead of the url of the first post, I am assuming it has something to do with " 'fields' => 'ids' " but i have no idea as I don't write php:
function next_post_url() {
$next_post = get_next_post();
if(!$next_post){
$args = array(
'numberposts' => 1,
'post_type' => 'portfolio',
'order' => 'ASC',
'fields' => 'ids'
);
$first_post = get_posts( $args );
$next_post_url = $first_post[0];
}
else{
$next_post_url = get_next_post()->post_title;
}
return get_permalink($next_post->ID);}add_shortcode( 'next_post_url', 'next_post_url' );
Here you go please modify your php code as shown below.
function next_post_url() {
$next_post = get_next_post();
if (!$next_post) {
$args = array(
'numberposts' => 1,
'post_type' => 'portfolio',
'order' => 'ASC',
'fields' => 'ids'
);
$first_post = get_posts($args);
$post = $first_post[0];
} else {
$post = $next_post;
}
return get_permalink($post);
}
add_shortcode('next_post_url', 'next_post_url');

How can I see when a coupon is created in WooCommerce?

I am writing a custom plugin and I need to automatically send information about every newly created coupon. Until now, I can only choose a specific coupon by its name(e.g. 1234):
$coupon = new WC_Coupon("1234");
But I cannot seem to find how to get a coupon right after its created, without knowing its name, or at least how to get all of the available coupons. Can someone help?
May be this might help. Tested and it's working. This will return all coupons since coupons are saved as post_type shop_coupon.
$args = array(
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish',
);
$coupons = get_posts( $args );
Try to get using custom post type or directly mysql query.
1) Using mysql query
// Run a query on the postmeta table to get the id of every coupon that has the email in the customer_email restrictions
$couponlist = $wpdb->get_results("SELECT
`wp_postmeta`.`post_id`
FROM `wp_postmeta`
WHERE `wp_postmeta`.`meta_key` LIKE 'customer_email'
AND `wp_postmeta`.`meta_value` LIKE '%".$email."%'");
$couponarrayfinal = array( ); //Create an array of the ids so we can use wp_query to more quickly grab the data
// Add the ids to the array in a foreach loop
foreach( $couponlist as $key => $row) {
$value = $row->post_id;
$couponarrayfinal[] = $value ;
}
2) Using get_posts method
$arg = array(
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish');
$coupons_list = get_posts( $arg );
Try with this you will get the all the data
// WP_Query arguments
$args = array(
'post_type' => array('shop_coupon'),
'post_status' => array('publish'),
'posts_per_page' => '-1',
'order' => 'DESC',
'orderby' => 'id',
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// do something
$coupon = new WC_Coupon(get_the_ID());
$coupnCode = $coupon->code;
$coupnAmount = $coupon->amount;
$minAmount = wc_format_decimal($coupon->minimum_amount, 2);
$maximumAmount = wc_format_decimal($coupon->maximum_amount, 2);
$expire = $coupon->expiry_date;
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();

How to change Bulk Wordpress Post Status?

Is it possible to Published all Draft Posts using SQL or Function code? I tried using this code in my function file, but not works.
add_action('admin_init','wpse_244394');
function wpse_244394(){
$args = array('post_type'=> 'post',
'post_status' => 'draft',
'posts_per_page'=>-1
);
$draft_posts = get_posts($args);
foreach($draft_posts as $post_to_publish){
$query = array(
'ID' => $post_to_publish->ID,
'post_status' => 'publish',
);
wp_update_post( $query, true );
}
}
try to use "wp_publish_post( $post_id )" instead of "wp_update_post".
add_action('admin_init','wpse_244394');
function wpse_244394(){
$args = array('post_type'=> 'post',
'post_status' => 'draft',
'posts_per_page'=>-1
);
$draft_posts = get_posts($args);
foreach($draft_posts as $post_to_publish){
wp_publish_post( $post_to_publish->ID );
}
}

Function wp_post_update breake the foreach loop, no errors, no id response. Why?

In my wordpress plugin i have follow code:
$args = array(
'post_status' => 'draft',
'category' => 1,
'post_type' => array('page', 'post', 'attachment' ),
'posts_per_page' => -1,
);
$allposts = get_posts($args);
foreach ( $allposts as $key => $post ) {
$update = [];
$update['ID'] = $post->ID;
$update['post_title'] = 'post title';
$update['post_name'] = 'post-name';
$post_id = wp_update_post( $update , true);
//fail, loop stopped without any errors
var_dump($post_id); //never happens
}
$allposts contains valid array of post objects
The first iteration update first post, but wp_update_post returns absolutely nothing, no errors, no post id, nothing
so next iteration never starts...
that code has works perfect before, but at one of the moment has broken
what happened here?
p.s. on other blog this code still works perfect
check this below code working in my system with publish post status.
add_action ('init',array( $this, 'updateAllPost'));
public function updateAllPost()
{
$args = array(
'post_status' => 'draft',
'category' => 1,
'post_type' => array('page', 'post', 'attachment' ),
'posts_per_page' => -1,
);
$allposts = get_posts($args);
foreach ( $allposts as $key => $post ) {
$update = array(
"ID"=>$post->ID,
"post_title"=>"post title",
"post_name"=>"post-name"
);
$post_id = wp_update_post( $update , true);
//fail, loop stopped without any errors
var_dump($post_id); //never happens
}
}

wordpress create duplicate post on save / update

I know this might seem strange to some, but i would like to duplicate a post on creation.
When a post is created, i would like to duplicate it appending new data to the title, as well as updating meta fields and changing the taxonomy it is in.
Here is what i have done so far:
add_action('wp_insert_post', 'my_add_custom_fields');
function my_add_custom_fields($post_id)
{
if ( $_POST['post_type'] == 'products' ) {
$my_post = array(
'post_title' => get_the_title(),
'post_content' => '',
'post_status' => 'publish',
'post_type' => 'products',
);
$id = wp_insert_post($my_post);
update_post_meta($id,'keywords', get_the_title());
wp_set_object_terms($id, 'New Term Here', 'platform');
}
return true;
}
The issue i have is this creates an endless loop, creating the new post thousands of times and wont stop until i restart apache.
Is there away around this?
You need some sort of control for this to stop it looping. e.g. set a global value to count
$GLOBALS['control']=0;
add_action('wp_insert_post', 'my_add_custom_fields');
function my_add_custom_fields($post_id)
{
if ( $_POST['post_type'] == 'products' ) {
//if control is on third iteration dont proceed
if($GLOBALS['control']===2)
return;
//add control here!
$GLOBALS['control']++;
$my_post = array(
'post_title' => get_the_title(),
'post_content' => '',
'post_status' => 'publish',
'post_type' => 'products',
);
$id = wp_insert_post($my_post);
update_post_meta($id,'keywords', get_the_title());
wp_set_object_terms($id, 'New Term Here', 'platform');
}
return true;
}

Categories