I am trying to do a conditional check (checking if post with same post title exists) before running wp_insert_post() but it still accepts the insertion even if existing posts are found. I tried using post_exists(), but this function breaks the entire page for some reason. What am I doing wrong?
footer.php:
<?php
$statusmessage = '';
if (isset($_POST['footer-email'])){
$footer_email = $_POST['footer-email'];
$args = array(
"post_title" => $footer_email,
"post_type" => 'subscriptions',
"post_status" => 'publish',
);
$query = new WP_Query( $args );
if($query->have_posts()) {
$statusmessage = '<p class="subscription-confirmation">You have already signed up.</p>';
}
else {
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
} // end else
wp_reset_postdata();
} // end if isset footer email
?>
You can use post_exists(). check the below cood.
<?php
$statusmessage = '';
if (isset($_POST['footer-email'])){
$footer_email = $_POST['footer-email'];
if( ! post_exists( $footer_email ) ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
} // end if isset footer email
You can use get_page_by_title() to fetch subscribers by title.
$statusmessage = '';
if ( isset( $_POST['footer-email'] ) ){
$footer_email = $_POST['footer-email'];
$subscribers = get_page_by_title( $footer_email , OBJECT, 'subscribers' );
if( !$subscribers->ID ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
}
OR custom wpdb query.
global $wpdb;
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $footer_email . "'" );
if( !$postid ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
Related
I have created a Wordpress site where users register on the front-end and add information about themselves. On registration I am forcing the user_nicename to be name-surname. I am then automatically creating 2 custom post types that act as profile pages for the new users. I am using the user_nicename as the title of both.
The problem is obviously if two people register with the same name.
So I would like to check the database before the user_nicename is updated to check if it already exists. If it does I would like to add an integer (in sequence) to the end of the user_nicename.
For instance:
John-Smith
John-Smith-2
John-Smith-3
Etc.
The code I have tried is as follows, but I'm not having any luck. The custom post types generate fine, but the user_nicename is not being appended with an integer.
Any help would be much appreciated!
add_action( 'user_registration_after_register_user_action', 'ur_insert_username', 1, 3 );
function ur_insert_username( $valid_form_data, $form_id, $user_id ) {
global $wpdb;
$firstname = isset( $valid_form_data['first_name'] ) ? $valid_form_data['first_name']->value : '';
$lastname = isset( $valid_form_data['last_name'] ) ? $valid_form_data['last_name']->value : '';
{
$custom_nicename = sanitize_title_with_dashes( $firstname . '-' . $lastname);
{
$i = 1;
do {
$user = get_user_by('login', $custom_nicename);
if( ! empty( $user ) ) {
$i++;
$custom_nicename = $custom_nicename ."-" . $i;
}
}
while ( ! empty( $user ) );
}
$wpdb->update(
$wpdb->users,
['user_nicename' => $custom_nicename],
['ID' => $user_id]
);
}
{
$user_post_athlete = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_id
);
$user_post_rivalry = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'rivalry', // <- change to your cpt
'post_author' => $user_id
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post_athlete );
$post_id = wp_insert_post( $user_post_rivalry );
}
}
I will suggest you to manage post type for user profile using post_author.
I guess you are adding post by code using wp_insert_post , so add "post_author" field to store user id in it. Wordpress will automatically manage slug of two different posts with same title. And you can associate posts and user using "post_author" field.
https://developer.wordpress.org/reference/functions/wp_insert_post/
Editing my answer
get_user_by('login' will not work reason being login is 'username' and you need to search 'nickname'. You need to get user details by below code
$user_data=get_users(array(
'meta_key' => 'nickname',
'meta_value' => 'jaytesh'
));
echo "user id is".$user_data[0]->ID;
And Your code will change to (approx code)
add_action( 'user_registration_after_register_user_action', 'ur_insert_username', 1, 3 );
function ur_insert_username( $valid_form_data, $form_id, $user_id ) {
global $wpdb;
$firstname = isset( $valid_form_data['first_name'] ) ? $valid_form_data['first_name']->value : '';
$lastname = isset( $valid_form_data['last_name'] ) ? $valid_form_data['last_name']->value : '';
{
$custom_nicename = sanitize_title_with_dashes( $firstname . '-' . $lastname);
{
$i = 1;
do {
$user_data=get_users(array(
'meta_key' => 'nickname',
'meta_value' => $custom_nicename
));
if( ! empty( $user_data[0]->ID ) ) {
$i++;
$custom_nicename = $custom_nicename ."-" . $i;
}
}
while ( ! empty( $user_data[0]->ID ) );
}
$wpdb->update(
$wpdb->users,
['user_nicename' => $custom_nicename],
['ID' => $user_id]
);
}
{
$user_post_athlete = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_id
);
$user_post_rivalry = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'rivalry', // <- change to your cpt
'post_author' => $user_id
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post_athlete );
$post_id = wp_insert_post( $user_post_rivalry );
}
}
i am using this code to create a post in DWQA plugin? but, my theme editer is going to die. what's the problem i am facing?
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
// Create a new post
$post = array(
'post_content'=> $post_content,
'post_title' => $post_title,
'post_author' => $post_author,
'post_category' => $post_category,
'post_type' => 'dwqa-question',
'post_status' => 'draft',
'post_date' => 'date_created',
'show_in_menu' => 'post-new.php?post_type=dwqa-question',
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
I was just a thought, but I have not tried.
you need / add functions in wp-includes / query.php
Such code:
function query_post($post_id) {
$GLOBALS['wp_query'] = new WP_Query();
return $GLOBALS['wp_query']->query($post_id);
}
I'm using the function below to convert WP-comments to WP-posts. I want it to be fired when "approving" a comment. (now it is whenever the plug-in is activated in WP).
So really I'm wondering how to ad my function to this action from line 47 of the edit-comments.php:
foreach ( $comment_ids as $comment_id ) { // Check the permissions on each
if ( !current_user_can( 'edit_comment', $comment_id ) )
continue;
switch ( $doaction ) {
case 'approve' :
wp_set_comment_status( $comment_id, 'approve' );
$approved++;
break;
[...]
}
}
Plug-in function:
register_activation_hook( __FILE__, 'convert_to_posts' );
function convert_to_posts(){
$comments = get_comments();
foreach($comments as $comment)
{
$post = get_post($comment->comment_post_ID);
$title = get_comment_meta( $comment->comment_ID, 'title', true );
$content = $comment->comment_content;
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1
);
wp_insert_post( $my_post );
// wp_delete_comment( $comment->comment_ID );
}
}
I'm using Advanced custom fields and custom post types ui, I need to generate a post name with the author's name in it, however this just prints "Solicitud", it seem like my variable $autor gets no value, is there any way I can fix this?
function my_pre_save_post( $post_id ) {
$post2 = get_post($post_id);
$autor=$post2->author;
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud' . $autor,
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
And, here is the code I use to create the form, I'm using acf_form:
$current_inv = $_GET['invid'];
/**
* Template Name: Solicit
*/
acf_form_head();
get_header();
?>
<div id="primary">
<div id="content" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php acf_form(array(
'post_id' => 'new',
'field_groups' => array( 243 ),
'submit_value' => 'Crear el ticket'
)); ?>
<?php endwhile; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>
Try using 'post_author' instead of 'author'. And also make sure that WP_Debug is set to TRUE while you're developing.
Here's a long version
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud',
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// Once we save, retrieve the original post so we can take the post_author
$post2 = get_post($post_id);
// Use post_author
$autor = $post2->post_author;
// Update the post with the new title
wp_update_post(array('ID' => $post_id, $post2->post_title . $autor));
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
Slightly shorter version which uses the current logged in user's username.
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
$current_user = wp_get_current_user();
$author = $current_user->user_login; // OR [user_firstname, user_lastname, display_name]
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud' . $author,
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
References:
http://codex.wordpress.org/Class_Reference/WP_Post
http://www.advancedcustomfields.com/resources/tutorials/using-acf_form-to-create-a-new-post/
http://codex.wordpress.org/Function_Reference/wp_get_current_user
I am trying to insert a post/page and then save the post id as an option, but the option is not saving to the database.
I am able to create the page and get the ID of it, but I am unable to save that ID to the options. The class is called at "init" and the constructor is as follows:
class Recipe{
public function __construct(){
$favorites_id = get_option("favoritesid");
if($favorites_id <= 0){
$my_post = array(
'post_title' => 'Favorites',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page'
);
$result_id = wp_insert_post( $my_post );
if($result_id > 0){
add_option("favoritesid", $result_id);
}
}
}
Test the code in the main plugin file: (//use array_push for option)
class Recipe{
public function __construct(){
add_action('init',[$this,'test']);
}
public function test(){
$favorites_id = get_option("favoritesid",[]);
if($favorites_id >= 0){
$my_post = array(
'post_title' => 'this is test',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page'
);
$result= get_page_by_title($my_post['post_title'],ARRAY_A, 'page');
if(is_null($result)) {
$result_id = wp_insert_post( $my_post );
if ( $result_id >= 0 ) {
update_option( "favoritesid", $result_id );
}
}
else return false;
}
}
}
new Recipe;