Hello there, in this tutorial we will learn How to Create Function to Get Post Metadata Using PHP to Get Value by Key Here is an example function in PHP that retrieves post metadata from a MySQL database using the mysqli extension and a specified key:
PHP CODE
<?php
function get_post_metadata($mysqli, $post_id, $meta_key) {
$query = "SELECT meta_value FROM wp_postmeta WHERE post_id = ? AND meta_key = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("is", $post_id, $meta_key);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
return $row['meta_value'];
} else {
return false;
}
}
// Example usage:
$mysqli = new mysqli("localhost", "username", "password", "database_name");
$post_id = 123;
$meta_key = "_my_custom_field";
$meta_value = get_post_metadata($mysqli, $post_id, $meta_key);
if ($meta_value) {
echo "The value of '$meta_key' for post $post_id is: $meta_value";
} else {
echo "No value found for key '$meta_key' and post $post_id";
}
?>
This function takes three arguments:
- $mysqli (an instance of the mysqli class)
- $post_id (the ID of the post whose metadata is being retrieved), and
- $meta_key (the name of the metadata key to retrieve).
The function constructs a SELECT query that searches the wp_postmeta table for a row with a matching post ID and meta key. It then binds the $post_id and $meta_key variables to placeholders in the query using bind_param(), executes the query with execute(), and retrieves the result set with get_result().
If the result set contains one or more rows, the function retrieves the first row's meta_value field and returns it. Otherwise, the function returns false to indicate that no value was found for the specified key.