已知meta_key和post_id,如何获取短码所需的meta_value?
Hey there! Since you already have the post_id and meta_key ready to go, fetching the corresponding meta_value (your shortcode, in this case) is totally doable. Let’s break down the most common, reliable ways to handle this, depending on your setup:
If you’re working within a WordPress environment, the get_post_meta() function is the safest and easiest way to get what you need—it handles serialization, database prefixes, and edge cases automatically.
Here’s a quick, actionable example:
// Replace these with your actual values $target_post_id = 123; $target_meta_key = 'your_shortcode_meta_key'; // Fetch the single meta value (use `true` to get a string instead of an array) $shortcode_value = get_post_meta($target_post_id, $target_meta_key, true); // Optional: Verify the value exists before using it if (!empty($shortcode_value)) { echo "Your shortcode is: " . $shortcode_value; } else { echo "No meta value found for this post and key."; }
The third parameter (true) tells the function to return a single, clean value instead of an array—perfect for shortcodes, which are almost always stored as plain strings.
If you can’t use WordPress functions (e.g., a standalone script or external tool), you can query the wp_postmeta table directly with SQL. Just remember to replace wp_ with your actual database prefix if it’s different:
SELECT meta_value FROM wp_postmeta WHERE post_id = 123 AND meta_key = 'your_shortcode_meta_key';
- Double-check that your
post_idis a valid integer and yourmeta_keyis spelled exactly (it’s case-sensitive!) - If your shortcode was stored as serialized data,
get_post_meta()will automatically unserialize it for you—if you’re using raw SQL, you’ll need to handle that manually in your code - Some plugins store custom meta in their own tables, so confirm your data lives in
wp_postmetafirst if you’re hitting issues
内容的提问来源于stack exchange,提问作者Michiel O

