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;
}
Related
I'm trying to add a feature to my Wordpress website, that every time I add a post (custom post type), another post (different custom post type) is created.
I have tried adding an action in my function file but it does not seem to work.
functions.php
function add_notification($post_id) {
global $wpdb;
$post_type = get_post_type($post_id);
if($post_type == 'exercises'){
$title = "BLA";
$post_id_new = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'notification'
)
);
}
}
add_action('publish_post', 'add_notification');
I have also tried it with other hooks like new_to_publish and publish_post
With that I was expecting to have a new post (notification) when I add an exercise post.
I think it's something silly I'm forgetting but it's been like 3 days that I'm stuck in this problem.
For custom post type we have to use hook like
add_action('publish_custom-post-name','function');
In your case you have to use Like Below
function add_notification($post_id) {
global $wpdb;
$post_type = get_post_type($post_id);
if($post_type == 'exercises'){
$title = "BLA";
$post_id_new = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'notification'
)
);
}
}
add_action('publish_exercises', 'add_notification');
Please Try this. If any query feel free to ask.
I created a function, which duplicate products for specific users, when another user submit a post form.
In general I don't have issues to duplicate the products. When user ID 151 submit the post form, the product is duplicated for the other two users in the array under variable $relatedVendors. However, I have one issue within the function. As you can see I take the wpuf form ID from the original product and would like to store this id also for the other duplicated products (posts). For this case I use get_post_meta for the original post and then add_post_meta for the duplicated posts in the foreach loop. Now my issue is, that the meta key is populated for the duplicated posts, but the wpuf ID is not in the value field.
I tried to figure out, what the issue is. So the add_post_meta seems to work, because in one run I have hard coded an integer instead of $wpuf variable. In this case the hard coded id was stored in the meta value field. The same works fine for the second add post value "catalog".
For me it looks like that the get_post_meta is not working. I moved this part right below get the user id, then within the if state and within the foreach loop. I changed the priority as well. So, know I'm asking for help, why the get post is not working.
add_action('save_post', 'myWoo_duplicatePost', 10, 2);
function myWoo_duplicatePost($postID, $post) {
$current_user = wp_get_current_user();
if (isset($post->post_type) && $post->post_type == 'product' && $post->post_modified_gmt == $post->post_date_gmt && $current_user->ID == 151 ) {
$relatedVendors = array(114,88);
if ($post != null) {
remove_action('save_post', 'myWoo_duplicatePost', 10, 2);
foreach ($relatedVendors as $vendor) {
$args = array(
'comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $vendor,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => 'publish',
'post_title' => $post->post_title,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);
$new_post_id = wp_insert_post( $args );
$wpufID = get_post_meta($post_id, '_wpuf_form_id', true );
add_post_meta( $new_post_id, '_wpuf_form_id', $wpufID );
add_post_meta( $new_post_id, '_visibility', 'catalog' );
}
}
add_action('save_post', 'myWoo_duplicatePost', 10, 2);
}
}
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.
Well am creating my first wordpress plugin, which should create a page (relatively large) on activation.
Currently i can create a file using :
$_p['post_title'] = $the_page_title;
$_p['post_content'] = '<h1>PAGE CONTENT</h1>';
$_p['post_status'] = 'publish';
$_p['post_type'] = 'page';
$_p['comment_status'] = 'closed';
$_p['ping_status'] = 'closed';
$_p['post_category'] = array(1); // the default 'Uncatrgorised'
// Insert the post into the database
$the_page_id = wp_insert_post( $_p );
The problem is, I cant put all the content of the file(which is large) as string to 'post_content' index. I want to know if there is a way, where i can simply either:
'post_content' => link to the file in my plugin directory
'post_content' => call a function which will return html content as string :( [worst case]
OR, Some more simpler way to achieve the objective.
Please help me.
Well, what i did to solve the problem is:
//**SECTION : 1**
function user_login_foo() {
return get_login_form(); // get_login_form() function will return the html template i want to display.
}
add_shortcode('user_login', 'user_login_foo'); // created a shortcode
**// SECTION: 2**
function get_login_form()
{
ob_start(); ?>
<h3><?php __('Login'); ?></h3>
<form action="" method="post">
<fieldset>
// the login form comes here
</fieldset>
</form>
<?php
return ob_get_clean();
}
function validate_login_user() {
// the login validation logic comes here
}
add_action('init', 'validate_login_user');
SECTION 1: registered a shortcode that will call a function [say,foo1()] and return the value.
The function foo1() calls another a function [say foo2()] which returns a clean html form in response to the call (when the shortcode is called).
SECTION 2: In this section I defined the function foo2(), within which the html form [login form] is defined and returned to foo1() [where it is displayed].
Then i created an action [ add_action('init', 'validate_login_user'); ] which will call the function validate_login_user() on initialization, inside this function i checked for isset(METHOD[username]) and isset(METHOD[password]) and then do respective logic.
Like this i created multiple [shortcodes] for each of the pages I wanted to create at the time of activation,
Then :
**step 1:** register_activation_hook(__FILE__,'activation_plugin');
**step 2:** activation_plugin(){
'390' => [ // '390' is page id
'post_title' => 'Page title say login',
'post_content' => "[user_login]",
'post_status' => 'publish',
'post_type' => 'page',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_category' => array(1)
],
'391' => [
'post_title' => 'page title 2',
'post_content' => "[short_code2]",
'post_status' => 'publish',
'post_type' => 'page',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_category' => array(1)
],
// like this add multiple shortcodes
}
// this foreach will create all the pages
foreach ($_ as $key => $value) {
$the_page_title = $value['post_title'];
$the_page_name = $value['post_title'];
// the menu entry...
delete_option($value['post_title']);
add_option($value['post_title'], $the_page_title, '', 'yes');
// the slug...
delete_option($value['post_title']);
add_option($value['post_title'], $the_page_name, '', 'yes');
// the id...
delete_option($key);
add_option($key, '0', '', 'yes');
$the_page = get_page_by_title( $the_page_title );
if ( ! $the_page ) {
$the_page_id = wp_insert_post( $value );
}
else {
$the_page_id = $the_page->ID;
$the_page->post_status = 'publish';
$the_page_id = wp_update_post( $the_page );
}
delete_option( $key );
add_option( $key, $the_page_id );
}
Create Page On Plugin activation with content
$page_content= 'Content of page';
$demo_page = array(
'comment_status' => 'closed',
'ping_status' => 'closed' ,
'post_author' => 1,
'post_content' => $page_content,
'post_date' => date('Y-m-d H:i:s'),
'post_name' => 'page_name',//display on address bar
'post_status' => 'publish' ,
'post_title' => 'Page Display Name',
'post_type' => 'page',
);
//insert page and save the id
$demo_page_value = wp_insert_post( $demo_page, false );
//save the id in the database
update_option( 'testpage', $$demo_page_value );
You Use and Guide and read this link How to Create plugin and pages https://codex.wordpress.org/Creating_Options_Pages
i'm doing an webapp that works with a wordpress website.
Until yesterday all works like a charm, but from today, when i save the post on wordpress db, it now not working...
Not give me error (php error or wordpress error), but simply a white page.
This is my full code:(sorry for many commented lines and echo, but i'm testing)
The important part:
// Create post object
$my_post = array(
'post_title' => $article_title,
'post_name' => $article_title,
'post_content' => $article_content,
'post_status' => 'pending',
'post_author' => 1
);
// Insert the post into the database
wp_insert_post($my_post, TRUE);// try first time
$post_status = "pending";
$post_type = "post";
$post_parent = "0";
$post_ID = (int) $wpdb->insert_id;
echo $post_ID; die;
Yesterday with a simple wp_insert_post(my_post); all worked fine, today (of course i think i edited some files...or i don't now), not works more and not give me error.
What do you think ?
Thank you, really!
EDIT: The problem was that i not insert post_category and wp need it!
You can capture the $post_id with the wp_insert_post() function...
$post_ID = wp_insert_post($my_post, TRUE);// try first time
Then you can dump out the $post_ID variable to get the ID or the error.
var_dump($post_ID);
add_action( 'init', 'my_func' );
function my_func() {
$my_post = '';
if( get_page_by_title($article_title,'OBJECT','post') == NULL )
$my_post= array(
'post_title' => $article_title,
'post_name' => $article_title,
'post_type' => 'post',
'post_content' => $article_content,
'post_status' => 'pending',
'post_author' => 1
);
$post_id = wp_insert_post( $my_post );
echo 'Post ID - '.$post_id;
}