wp_insert_post failing to create CPT
-
Hello, I’m developing a custom theme for my website. I’m running into challenges when trying to use the wp_insert_post() function to convert MySQL tables into a Custom Post Type named “data.”
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>
- The topic ‘wp_insert_post failing to create CPT’ is closed to new replies.