I am making a plugin in wordpress. And I am trying to get the post id when I click the publish button on the add new post
. And now, I get an internal error(500) when I use the get post function.
I am using_POST['post']
now, but how can I use the wordpress function to get the post id?
Here is my code:
//require the php
require_once( FACEBOOK_API_PLUGIN_DIR . 'js/databaseConnection.php' );
Code on databaseConnection.php:
function get_post()
{
global $wp_query;
$thePostID = $wp_query->post->ID;
return $thePostID;
}
function try_insert($post_id)
{
$test02 = 333243;
$test03 = 222;
$link = @mysqli_connect(
'localhost',
'root',
'',
'wordpress'
) or die("connection failed");
$sql = "INSERT INTO post_data02 (post_id, condition_code) VALUES ('$post_id','$test03')";
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link -> error;
}
$link->close();
}
add_action( 'publish_post', 'try_insert', get_post());
Also, when I disable the get_post()
function I error will be gone. What am I doing wrong?
thanks,
You don't need get_post
at all and you are using the publish_post hook and add_action function incorrectly.
Additionally, have a look at the WPDB class. If your table is in the same database and schema as your WordPress tables you don't need to use mysqli_connect - WordPress has already connected to the database for you!
Note also that you should NEVER pass values into a string to be used as part of an SQL statement! This is a MASSIVE security risk! ALWAYS use prepared statements and parameters (WPDB provides this as well).
Try this:
function try_insert($post_id, $post)
{
// Pull in the global WPDB variable WordPress creates
global $wpdb;
$test02 = 333243;
$test03 = 222;
/*
* Insert record into the table "post_data02" with the values:
* "post_id" => The ID in $post_id passed by WordPress,
* "condition_code" => The number in $test03 (currently 222)
*/
$insert = $wpdb->insert( 'post_data02',
[ 'post_id' => $post_id, 'condition_code' => $test03 ],
[ '%d', '%d' ]
);
if( $insert !== false ) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link -> error;
}
}
add_action( 'publish_post', 'try_insert', 10, 2);
Please re-read the links I provided above as they provide excellent examples and show you how to use the functions, methods, hooks, etc.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments