When I run this code on an active p[age template (eg the contact page), the code works as intended and the tables are converted into new posts under the data CPT. The challenge I’m having is that when I try to run this same code from a non page template file, none of the tables are converted into posts and I do not receive any errors feedback.
I have isolated the $dbName variable and determined this portion is working as intended. Similarly, I have also been able to isolate the $tables array and determined the table names are being extracted as expected. Beyond these items, I have not been able to identify the exact issue that is preventing these tables from being inserted as “data” CPTs when run in a non page template file.
Some preliminary research has me thinking that this problem may have something to do with differences in core WordPress functions and class that depend on which type of file is being loaded (ie page vs other). I have tried to fix the issue by explicitly loading in wp-load.php, but this does not seem to have fixed the issue.
I greatly appreciate any assistance on this issue and will be happy to provide any additional information that may be needed to better uncover a solution.
My full code for this file is located at: https://www.codebin.co/code/2563e3c (Note: codebin marked this file as HTML; it is PHP). I have also included below a snippet of the remaining code after the two isolated items mentioned above.
<code>
//Query table data by looping through $tables to get each table name
for ($i = 0; $i < count($tables); $i++) {
$sql = "SELECT * FROM $tables[$i]
";
$result = $con->query($sql);
if ($result->num_rows > 0) {
$json_string = json_encode($result->fetch_all());
$newPost = array(
'post_title' => $tables[$i],
'post_content' => $json_string,
'post_status' => 'publish',
'post_type' => 'data',
'comment_status' => 'closed'
);
//Insert the post into WP database
$post_id = wp_insert_post($newPost);
}
}
$con->close();
</code>
]]>I’ve been facing a weird problem with the function wp_insert_post();
It seems to do a duplicate of the created post.
Here is the code i’m using:
function create_post(){
$args = [
'post_title' => 'test',
'post_content' => 'ok',
'post_type' => 'post',
'post_status' => 'draft',
'post_author' => 1
];
$post = wp_insert_post($args, true, false);
print_r($post);
}
create_post();
It’s on fresh wordpress install, using last version, added directly in the functions.php file.
Also noticed that when i comment the “create_post()” function and reload the page, it still runs one more time. A second reload and it’s not running anymore.
I’ve been digging the problem, and it seems that it’s actually not the wp_insert_post() functions that’s called multiple times (edited that core function, printed something, and there was only one output).
I don’t really have the time to dig more, and for now, i’ll be using wpdb directly.
Am i the only one with that problem, or am i missing something ?
]]>First time reloading, adding a new post.
Second time reloading, adding another 2 new posts.
Third time reloading, adding 4 new posts……
The following is my code in plugin/my_plugin.php:
function example_function(){
/*******************************************************
** POST VARIABLES
*******************************************************/
$postType = 'post'; // set to post or page
$userID = 1; // set to user id
$categoryID = '3'; // set to category id.
$postStatus = 'future'; // set to future, draft, or publish
$leadTitle = 'Exciting new post today: '.date("n/d/Y");
$leadContent = '<h1>Vacations</h1><p>Vacations are the best thing in this life.</p>';
$leadContent .= ' <!--more--> <p>Expensive they are, but they are totally worth it.</p>';
/*******************************************************
** TIME VARIABLES / CALCULATIONS
*******************************************************/
// VARIABLES
$timeStamp = $minuteCounter = 0; // set all timers to 0;
$iCounter = 1; // number use to multiply by minute increment;
$minuteIncrement = 1; // increment which to increase each post time for future schedule
$adjustClockMinutes = 0; // add 1 hour or 60 minutes - daylight savings
// CALCULATIONS
$minuteCounter = $iCounter * $minuteIncrement; // setting how far out in time to post if future.
$minuteCounter = $minuteCounter + $adjustClockMinutes; // adjusting for server timezone
$timeStamp = date('Y-m-d H:i:s', strtotime("+$minuteCounter min")); // format needed for WordPress
/*******************************************************
** WordPress Array and Variables for posting
*******************************************************/
$new_post = array(
'post_title' => $leadTitle,
'post_content' => $leadContent,
'post_status' => $postStatus,
'post_date' => $timeStamp,
'post_author' => $userID,
'post_type' => $postType,
'post_category' => array($categoryID)
);
/*******************************************************
** WordPress Post Function
*******************************************************/
$post_id = wp_insert_post($new_post);
/*******************************************************
** SIMPLE ERROR CHECKING
*******************************************************/
$finaltext = '';
if($post_id){
$finaltext .= 'Yay, I made a new post.<br>';
} else{
$finaltext .= 'Something went wrong and I didn\'t insert a new post.<br>';
}
echo $finaltext;
echo 'post_id is:'.$post_id;
}
add_action('init', 'example_function');
Does anyone help me solve this question?
I just want to add a new post after every reload.
Thanks
My code in my custom theme (functions.php) [only example]:
$posts = array(
'141th',
// ...
'3rd',
'2nd',
'1st'
);
foreach( $posts as $post ) {
wp_insert_post( array( 'post_title'=> $post ) );
}
My posts list:
141
139
140
137
138
...
1
I would like (in order):
141
140
139
138
...
1
Why? What is the problem and how to solving?
Thanks.
]]>The first 25 posts is uploaded, but have a 400 post.
What is the problem?
The source code:
foreach( videos( $_POST [ 'profile_id' ], $url ) as $key=> $video ) {
$args = array(
'post_status'=> 'publish',
'post_type'=> 'post',
'meta_key'=> 'video_id',
'meta_value'=> $video [ 'id' ]
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {} else {
$postarr = array(
'post_title'=> $video [ 'title' ],
'post_status'=> 'publish',
'meta_input'=> array(
'video_id'=> $video [ 'id' ],
'thumb'=> $video [ 'thumb' ],
'video_url'=> $video [ 'url' ],
'video_preview'=> $video [ 'video_preview' ],
'price'=> $video [ 'price' ],
'duration'=> $video [ 'duration' ],
'profile_id'=> $profile_id
)
);
wp_insert_post( $postarr );
}
wp_reset_postdata();
}
Thanks.
]]>The application is quite large, but I’ve boiled it down for the purposes of this question. It runs outside of WP Core, only loading it while running, through wp-load.php.
require_once( "../wp-load.php" );
$blog_id = 2;
switch_to_blog( $blog_id );
$lang = 'en';
$new_pr = wp_insert_post(
array(
'post_author' => 1,
'post_status' => 'publish',
'post_type' => 'pressreleases',
'post_date' => $this->publish_date,
'post_content' => $this->body,
'post_title' => $this->title,
'tax_input' => array(
'pr_categories' => $this->pr_category_id
)
)
);
var_dump( get_current_blog_id() ); // This returns (int)2, just like it should.
restore_current_blog();`
Here’s the problem:
No matter what I put in the $blog_id
variable, the release gets added to the blog with ID 1
.
Am I missing something here?
]]>What I can not do (so in this I need help):
This is the code I use to create the new post:
<?php
$content = do_shortcode( '[summary]' );
$date = date("d/m/Y");
$title_post = "Resumen diario - " .$date;
$id = wp_insert_post(array(
'post_title'=>$title_post,
'post_type'=>'resumen',
'post_status'=>'publish',
'post_content'=> $content,
));
?>
Thanks a lot for your help.
]]>To write the post I use the WP function wp_insert_post( $wp_post_array, true );
.
Inside the script at various stages I also use wp_get_attachment_image_src($image_id, $size)[0];
, wp_get_attachment_metadata($image_id);
and wp_get_attachment_image( $image_id, 'large', false, $image_attr );
but to upload the images and create their metadata I wrote this custom function below…
I must have messed up somewhere because I get a 500 Connection Timeout error when I run this code (even though it is only 3 images that are less than 1Mb each in size).
Can somebody spot what I am doing wrong? Thank you for your eyes and experience.
function insert_WP_Images_Data( $post_id, $image_url ) {
global $writer_WP_id;
$upload_dir = wp_upload_dir();
if ( isset($image_url) && isset($post_id) ) {
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir['path']))
$file = $upload_dir['path'] . '/' . $filename;
else
$file = $upload_dir['basedir'] . '/' . $filename;
$image_data = file_get_contents( $image_url );
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_author' => $writer_WP_id,
'post_content' => '',
'post_title' => $_SESSION['artist'],
'post_status' => 'inherit',
'post_name' => pathinfo($image_url)['filename'],
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $post_id,
'guid' => $upload_dir['url'].'/'.$filename
);
// 'post_title' => sanitize_file_name($filename),
$image_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once( ABSPATH.'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $image_id, $file );
$res1 = wp_update_attachment_metadata( $image_id, $attach_data );
$res2 = set_post_thumbnail( $post_id, $image_id );
return $image_id;
} else {
echo '<span class="error">No post is selected or image is selected</span>';
}
}
I have already tried increasing my server execution time in cPanel (200, 600) and via .htaceess (300) but nothing works…
]]><?php
// Load WordPress
require_once("../../../wp-load.php");
require_once ABSPATH . '/wp-admin/includes/taxonomy.php';
$my_post = array(
'post_title' => 'The post title via wp_insert_post Hello World!',
'post_content' => '<h4>Place all your body content for the post in this line.</h4>
[wbcr_snippet id="106" url="flebaixgtscj"] ',
'post_status' => 'publish',
'post_author' => $user_id,
'post_category' => array(9),
'post_type' => 'post', // defaults to "post". Can be set to CPTs.
'comment_status' =>'closed'
);
// Insert the post into the database
$id=wp_insert_post( $my_post );
echo "post id: ".$id."<br>";
?>
This custom_post.php file is located at the wp theme folder of specific site.
How to do this ? please help.
]]>