Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Get Meta Key Value While Saving Post

Think about what you’re doing here. You’re hooking into the time which WordPress is saving a post. You need to use get_post_meta() to check if the saving post has that required meta key.

If you get nothing back, or get_post_meta() returns false, then you need to add your post meta for this saving post using add_post_meta().

If you get something back, check the values of get_post_meta(), Are they appropriate? Do they need to be changed? This is where you determine if you need to call update_post_meta().

Once you have validated that your saving post has meta data available to use, THEN you should continue with updating your custom database table… And the same rules apply from the post meta, with your custom database table.

Check for data in your custom database table. Then determine whether your custom database table should be inserted with data or updated with data.

Based off the code you provided, I have tried to piece together an example for you to use.

function my_save_post($post_id, $post){
    global $wpdb;
    /* Not doing an auto save. */
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
        return;
    }
    /* Make sure we have the post data. */
    if(!isset($post)){
        return;
    }
    /* Validate the correct post type and make sure it's not a post revision. */
    if($post->post_type == 'post' && $post->post_status == 'publish' && !wp_is_post_revision($post_id)){

        /* Fetch the post meta for this post. */
        $meta = get_post_meta($post_id, 'banner_link', true);
        if(!$meta){
            // No meta for this post with the key of 'banner_link'. Add your post meta.
        } else{
            // Meta data with a key of 'banner_link' was found. Update your post meta.  
        }

        /* Meta data has either been added or updated. Fetch the data again. */
        $meta = get_post_meta($post_id, 'banner_link', true);

        /* Set the counter to 1. */
        $counter = 1;

        /* Check if data already exists for this post in the custom database table. */
        $my_data = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}banner_views WHERE postid = {$post_id}");
        if(!empty($my_data)){
            /* Update the custom database table, with data from this post. */
            $wpdb->update( 
                $wpdb->prefix.'banner_views', 
                array( 
                    'link' => $meta,
                    'view_count' => $counter,
                ),
                array('postid' => $post_id), 
                array(
                    '%s',
                    '%d'
                ),
                array('%d') 
            );
        } else{
            /* Initially insert the data for this post in the custom database table. */
            $wpdb->insert(
                $wpdb->prefix.'banner_views', 
                array( 
                    'postid' => $post_id,
                    'link' => $meta,
                    'view_count' => $counter,
                ),
                array(
                    '%d',
                    '%s',
                    '%d'
                )
            );
        }          
    }
}
add_action('save_post', 'my_save_post', 10, 2);

It’s not 100% complete, more specifically around the post meta. Hope this helps.

My personal opinion…

You should probably just store everything with post meta, unless there’s a legitimate reason to be storing it in a separate database table.

Note: You also need to do some work with your counter. Right now, you’re just always setting it as 1 no matter what.

Related Posts:

  1. Better post meta efficiency?
  2. Change post author without using wp_update_post()
  3. Update post meta within save_post action
  4. Bulk Post update_post_meta
  5. Ordering posts alphabetically by meta keys and title
  6. How to limit the number of posts that WP_Query gets?
  7. Should we trust the post globals?
  8. How to check if post meta key exists or not in wordpress database
  9. How to add category to: ‘wp-admin/post-new.php’?
  10. Random sort within an already sorted query
  11. How can I retrieve multiple get_post_meta values efficiently?
  12. Code to make a post sticky
  13. how to get a different html for odd/even posts?
  14. How to allow hidden custom fields to be added from wp-admin/post.php?
  15. Export WordPress Posts and Meta Information in CSV format
  16. Delete duplicated wp_postmeta record
  17. How to know if get_posts() failed?
  18. Will a large postmeta table slow a site down?
  19. Update all posts automatically when using post_meta
  20. What to use: wp_is_post_autosave( $post_id ) or DOING_AUTOSAVE?
  21. Using $wpdb to query posts with meta value containing current post_id
  22. Query posts from current year
  23. How to batch update post content with custom post meta value
  24. Change slug with custom field
  25. WordPress Number of Posts Not Changing With posts_per_page
  26. I have over 4000 posts, will querying some of them cause performance issues?
  27. Duplicate posts
  28. Looping through posts per category gives same posts for each category
  29. How to show posts rank based on custom field value
  30. Setting post meta data to random value during post status transition / on publish
  31. How can I pass $post object to ‘save_post’ add_action?
  32. Edit meta data does’t work with custom sql
  33. How do I create Comma Separated list of attached image ids?
  34. How to add posts to wp_query result?
  35. Trying to put an array into ‘post__in’ => array() query not working
  36. Human Time Diff, change mins to minutes
  37. Order post by year DESC and month ASC
  38. Change post format using custom field
  39. Have save_post write to database image meta [closed]
  40. Get the post_id of a new post
  41. Should ‘setup_postdata()’ be reset with ‘wp_reset_postdata()’?
  42. Does WP get all post_meta on POST page?
  43. How can I display a specific user’s first published post?
  44. Sanitizing `wp_editor();` Values for Database, Edit, and Display
  45. Query All users that has post
  46. Exporting Data from WordPress into a flat table
  47. Adding Multiple Values to a Post Meta Key
  48. wp_enqueue_media() slows down my WP site
  49. Using radio button meta data from a custom meta box
  50. How can I get all posts data from within a paginated search result?
  51. Search query – exact post title match
  52. publish_post conflicts with save_post
  53. Sorting posts alphabetical that have single digits
  54. Query posts from different categories in multisite
  55. Check if post exists
  56. posts_per_page doesnt work
  57. Sorting posts according to view counts not working
  58. PHP Notice error (when on 404 page)
  59. What Is meta_id In wp_postmeta?
  60. Display page content AFTER a loop of posts
  61. Only display posts after current date
  62. Get posts by multiple ID’s (query)
  63. Checking if a post with certain meta value exists
  64. How to start with post number x?
  65. Exclude posts with empty post_content in wp_query
  66. How to permanently delete a post meta entry?
  67. Only display a certain number of posts, dependent on how many posts there are available in a query
  68. Add custom field automatically (add_post_meta) with value based on number of words of article
  69. WordPress Orderby Numeric Value Not Working
  70. How to generate numbers indistinguishable for the IDs of the posts
  71. Improving WP_Query for performance when random posts are ordered
  72. Modify WP_Post before processing
  73. Save re-arranged draggable post items to wordpress database
  74. Should $found_posts be returned as string in ‘found_posts’ filter hook?
  75. I would like to give special promotion for the first 100 posts in my blog? Can anyone tell me how to do that?
  76. Change post_date to post_modified date on post template?
  77. Query how many items to show in shortcode
  78. Converting a dynamic piece of code using WordPress Loop into a static one using Post ID
  79. Get posts by name and taxonomy term
  80. WP_Query Authors OR Categories
  81. Get Posts that are in the current month or later
  82. How to get post bulk edit action trigger and get edited post ids?
  83. Sticky post appears twice
  84. do_shortcode within post query
  85. How Can I Query a Specific Page From a MultiPage paginated Post
  86. How can I sort posts by the date and a custom meta field?
  87. is there a way to show the the post title after the image?
  88. Most liked page not displaying posts
  89. Query get post,how to add comment box
  90. Force the “Choose from the most used tags” meta box section to always be expanded
  91. Meta value does not save for scheduled posts
  92. Custom Posts Query and meta_query Sort Order
  93. filter RSS feed in URL
  94. WordPress custom Query for Posts in Category display posts multiple times
  95. Updating post data on save (save_post vs wp_insert_post_data)
  96. How to compare two posts including their meta fields on a scalable base?
  97. get query() without post content?
  98. Getting value from get_post_custom
  99. Calling Different Custom Post Timestamps in a table
  100. How can I setup a relationship using categories in WordPress?
Categories posts Tags post-meta, posts, query, save-post
Where does the gallery shortcode gets its attachments from?
how to open page, defined in plugin, from dashboad widget

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress