I am trying to insert meta key value while saving or updating post but somehow it is not inserting meta value to link
column of my custom talbe called wp_banner_views
function get_publishing_id($post_id) {
global $wpdb;
global $post;
$post= get_post($post_id);
if ($post->post_type == 'post'
&& $post->post_status == 'publish') {
$meta = get_post_meta($post->ID, 'banner_link', true);
if(empty ($counter)) {
$counter = 1;
$wpdb->insert(
$wpdb->prefix . 'banner_views',
array(
'postid' => $post->ID,
'link' => $meta,
'view_count' => $counter,
),
array(
'%d',
'%s',
'%d'
)
);
}
}
}
add_action('save_post','get_publishing_id');
I am trying to make click and view counter for banner. I have done view counter but trying to create click counter. Any autosuggestion for that would be appropriated.
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 usingadd_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 callupdate_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.
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.