wp_insert_post function inserts the same post 2 times - wordpress

Here is my code:
function insert_post() {
global $wpdb;
if (!isset($_POST['data'])) {
exit;
}
$data = json_decode(stripslashes_deep($_POST['data']), true);
$title = $data['post_title'];
$content = $data['post_content'];
$img = $data['post_thumbnail'];
$attach_id = $data['post_thumbnail'];
$review_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_category' => array( 34 ),
'filter' => true
);
$post_id = wp_insert_post( $review_post );
$review = get_post( $post_id );
$avatar = wp_get_attachment_image( $img, 'full' );
$common_list = array();
$common_list['post'] = $review;
$common_list['post_thumbnail'] = $avatar;
$common_list['code'] = $code;
$common_list['fb'] = $fb;
$common_list['gender'] = $gender;
echo json_encode( $common_list);
exit;
}
add_action('wp_ajax_insert_post', 'insert_post');
add_action('wp_ajax_nopriv_insert_post', 'insert_post');
Problem is that wp_insert_post() function inserts the same post 2 times. Can't find solution. What can cause this?

I found a solution, here it is:
if (!get_page_by_title($title, 'OBJECT', 'post') ){
$review_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_category' => array( 34 ),
'filter' => true
)
}
;
Just checked whether a post with same title exists or not, if yes it doesn't call wp_insert_post.

Related

CF7 validate and store data

I am trying to make custom validation to cf7 form and then store data in a custom post type if everything is valid. My problem is that even when form inputs are not valid form still sends email and store its data. Can you help me with that. Below is my code. What should I use to validate inputs first and only then store data.
Store posted data:
function save_posted_data_ios( $posted_data ) {
if( isset($posted_data['menu-377']) == "IOS" ){
$args2 = array(
'post_type' => 'np_coupon_code',
'post_status' => 'publish',
'posts_per_page' => 1,
'meta_query' => array(
array(
'key' => 'np_ccode__email',
'value' => 'null',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'np_ccode__type',
'value' => 'IOS'
)
)
);
$posts_query2 = new WP_Query($args2);
$the_count_ios = $posts_query2->found_posts;
$query = new WP_Query($args2);
while ( $query->have_posts() ) : $query->the_post();
$id = get_the_ID();
$code = get_the_title();
endwhile;
if( isset($posted_data['your-email']) ){
update_post_meta($id, 'np_ccode__email', $posted_data['your-email']);
}
$to = $posted_data['your-email'];
$subject = 'Subject';
$body = $code;
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
return $posted_data;
wp_reset_query();
}
}
add_filter( 'wpcf7_posted_data', 'save_posted_data_ios' );```
Custom error:
function my_wpcf7_validate_ios( $result_ios, $tag ) {
$type = $tag['type'];
$name = $tag['menu-377'];
$args2 = array(
'post_type' => 'np_coupon_code',
'post_status' => 'publish',
'posts_per_page' => 1,
'meta_query' => array(
array(
'key' => 'np_ccode__email',
'value' => 'null',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'np_ccode__type',
'value' => 'IOS'
)
)
);
$posts_query2 = new WP_Query($args2);
$the_count_ios = $posts_query2->found_posts;
if ( $the_count_ios == 0 && $_POST['menu-377'] == "IOS"){
$result_ios->invalidate( $tag, wpcf7_get_message( 'invalid_ios' ) );
}
return $result_ios;
}
add_filter( 'wpcf7_validate_select*', 'my_wpcf7_validate_ios' , 10, 2 );
add_filter( 'wpcf7_messages', 'mywpcf7_ios_messages' );
function mywpcf7_ios_messages( $messages ) {
return array_merge( $messages, array(
'invalid_ios' => array(
'description' => __( "No IOS Coupons Left", 'contact-form-7' ),
'default' => __( 'No IOS Coupons Left.', 'contact-form-7' )
)
));
}

Create a page with child pages and have each child have it's own page template

I have some code that creates pages with child pages in WordPress. What i would like to do is have each child have its own page template.
As you see below, i am creating child pages of Script and Assets. Currently the child page is created with one page_Full.php added to everything but i would like to have Script and Assets have their own page template. Ideas would be helpful.
Thanks in advance.
function CreatePage(){
$post_title = $_POST['ProjectName'];
$post_excerpt = $_POST['ProjectDiscript'];
$tags = $_POST['TypeOption'];
$pages = array(
array(
'name' => $post_title,
'title' => $post_title,
'child' => array(
'script' => $post_title.'_Script',
'assets' => $post_title.'_Assets'
)
)
);
$template = array(
'post_type' => 'page',
'post_status' => 'publish',
'post_author' => $user_id,
'post_excerpt' => $post_excerpt,
'tags_input' => array($tags),
);
foreach( $pages as $page ) {
$exists = get_page_by_title( $page['title'] );
$my_page = array(
'post_name' => $page['name'],
'post_title' => $page['title'],
'page_template' => 'page_Full.php'
);
$my_page = array_merge( $my_page, $template );
$id = ( $exists ? $exists->ID : wp_insert_post( $my_page ) );
if( isset( $page['child'] ) ) {
foreach( $page['child'] as $key => $value ) {
$child_id = get_page_by_title( $value );
$child_page = array(
'post_name' => $key,
'post_title' => $value,
'post_parent' => $id,
'page_template' => 'page_Full.php'
);
$child_page = array_merge( $child_page, $template );
if( !isset( $child_id ) ) wp_insert_post( $child_page );
}
}
}
wp_die();
}
add_action( 'wp_ajax_CreatePage','CreatePage' );
Had the idea to create an array for every child page - and it seams to work. Perhaps there is still a better way but for the time being - This does the trick!
$pages = array(
array(
'name' => $post_title,
'title' => $post_title,
'child' => array(
'script' => array(
'Pname' => $post_title.'_Script',
'Ptemplate' => 'page_Full_Script.php'
),
'assets' => array(
'Pname' => $post_title.'_Assets',
'Ptemplate' => 'page_Full_Assets.php'
),
'settings' => array(
'Pname' => $post_title.'_Settings',
'Ptemplate' => 'page_Full_Settings.php'
)
)
)
);
Here is the child with sub arrays.
if( isset( $page['child'] ) ) {
foreach( $page['child'] as $key[] => $value ) {
$child_id = get_page_by_title( $value );
$child_page = array(
'post_name' => $value['Pname'],
'post_title' => $value['Pname'],
'post_parent' => $id,
'page_template' => $value['Ptemplate'],
);
$child_page = array_merge( $child_page, $template );
if( !isset( $child_id ) ) wp_insert_post( $child_page );
}
}
And here is where the child array is set as var to be iterated through so that the info can be inserted into the child_page var to be merged and the post inserted.
Thanks to any who took the time to review.
Cheers

get only featured image

I search internet, but I found only the reverse scenerio, the thing I want to do is that get only featured image in this query
$attachments = new WP_Query( array(
'post_parent__in' => $published,
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'posts_per_page' => 1,
'orderby' => 'rand',
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'no_found_rows' => true
) );
if ( $attachments->have_posts() ) {
$image = wp_get_attachment_image_src( $attachments->posts[0], $args[ 'size' ] );
if ( file_exists( $image[0] ) ) {
set_transient( $objects_key, $image, 3 * HOUR_IN_SECONDS );
}
}
}
You really don't want to mess with wp_query() if you can help it try this...
global $post;
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
if($post_thumbnail_id != null) {
$image = wp_get_attachment_image_src( $post_thumbnail_id, $args[ 'size' ] );
if ( file_exists( $image[0] ) ) {
set_transient( $objects_key, $image, 3 * HOUR_IN_SECONDS );
}
}
I am asuming that $objects_key and HOUR_IN_SECONDS are defined elsewhere

How to get_permalink of the wordpress page

I create WordPress page with this function:
function adv_activate_plugins(){
$post_details = array(
'post_title' => 'بازاریابی انلاین',
'post_name' =>'marketing4321',
'post_content' => '[marketing]',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page'
);
wp_insert_post( $post_details );
}
How to get_permalink of that page?
$id = wp_insert_post($post_details);
$permalink = get_permalink($id);
If you want to use it outside of your function:
function adv_activate_plugins(){
$post_details = array(
'post_title' => 'بازاریابی انلاین',
'post_name' =>'marketing4321',
'post_content' => '[marketing]',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page'
);
$id = wp_insert_post( $post_details );
return $id;
}
//the id of the new post
$new_post_id = adv_activate_plugins();
//get the permalink
$permalink = get_permalink($new_post_id);
Try with below code which would help your cause,
function get_permalink_by_post_name($post_name){
global $post;
global $wpdb;
$id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$post_name."'");
return get_permalink($id);
}
echo get_permalink_by_post_name('post-name');

Wordpress wp_update_attachment_metadata image width and height = 1?

Hello Friends I used to set post thumbnail programmatically.
this is my code.
foreach ($csv as $key => $value) {
$filename = "wp-content/uploads/images/".$value[8].".jpg";
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => 'this is the first project file.',
'post_status' => 'Published'
);
$my_post = array(
'post_title' => $value[0],
'post_content' => $value[2],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post_staff'
);
$post_id = wp_insert_post( $my_post );
$attach_id = wp_insert_attachment( $attachment, $filename,$post_id);
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
add_post_meta($post_id, '_thumbnail_id', $attach_id);
update_post_meta( $post_id, '_staff_name', $value[1] );
update_post_meta( $post_id, '_staff_city', $value[3] );
update_post_meta( $post_id, '_staff_postal_code', $value[4] );
update_post_meta( $post_id, '_staff_direct_line', $value[5] );
update_post_meta( $post_id, '_staff_fax', $value[6] );
update_post_meta( $post_id, '_staff_email', $value[7] );
$tagd = array( 9 );
wp_set_post_terms( $post_id, $tagd, 'department' );
if($value[3] == "St. John's, NL"){
$tagl = array( 8 );
}else if($value[3] == "Corner Brook"){
$tagl = array( 7 );
}
wp_set_post_terms( $post_id, $tagl, 'location' );
if(set_post_thumbnail( $post_id, $attach_id )){
echo "image set";
}
}
This is working fine but the imported feature image with size 1x1 width = 1 and height = 1
why it takes width and height is 1 automatically please help.
when i trying to get image using get_the_post_thumbnail the return image.
image is found but by default the image width = 1 and height = 1 take.
this is my code.
get_the_post_thumbnail( get_the_ID(), array(250,165))
Thank you.
This Function is used to import post with image in wordpress.
function fetch_media($file_url, $post_id) {
require_once(ABSPATH . 'wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
global $wpdb;
if(!$post_id) {
return false;
}
//directory to import to
$artDir = 'wp-content/uploads/importedmedia/';
//if the directory doesn't exist, create it
if(!file_exists(ABSPATH.$artDir)) {
mkdir(ABSPATH.$artDir);
}
//rename the file... alternatively, you could explode on "/" and keep the original file name
$extpop = explode(".", $file_url);
$ext = array_pop($extpop);
$new_filename = 'blogmedia-'.$post_id.".".$ext; //if your post has multiple files, you may need to add a random number to the file name to prevent overwrites
if (#fclose(#fopen($file_url, "r"))) { //make sure the file actually exists
copy($file_url, ABSPATH.$artDir.$new_filename);
$siteurl = get_option('siteurl');
$file_info = getimagesize(ABSPATH.$artDir.$new_filename);
//create an array of attachment data to insert into wp_posts table
$artdata = array();
$artdata = array(
'post_author' => 1,
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql'),
'post_title' => $new_filename,
'post_status' => 'inherit',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_name' => sanitize_title_with_dashes(str_replace("_", "-", $new_filename)), 'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql'),
'post_parent' => $post_id,
'post_type' => 'attachment',
'guid' => $siteurl.'/'.$artDir.$new_filename,
'post_mime_type' => $file_info['mime'],
'post_excerpt' => '',
'post_content' => ''
);
$uploads = wp_upload_dir();
$save_path = $uploads['basedir'].'/importedmedia/'.$new_filename;
//insert the database record
$attach_id = wp_insert_attachment( $artdata, $save_path, $post_id );
//generate metadata and thumbnails
if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
wp_update_attachment_metadata($attach_id, $attach_data);
}
//optional make it the featured image of the post it's attached to
$rows_affected = $wpdb->insert($wpdb->prefix.'postmeta', array('post_id' => $post_id, 'meta_key' => '_thumbnail_id', 'meta_value' => $attach_id));
}
else {
return false;
}
return true;
}
Pass value to this function like.
$file_name = 'full path of existing image';
$post_id = '1';
fetch_media($filename,$post_id);
Thank you.

Resources