You are usgin an undefined $post->ID
variable because there is no reference to any $post
object in your code; instead, use the $post_ID
variable retrieved in the function:
function on_jobs_publish( $post_ID ) {
global $wpdb;
$wpdb->insert(
'iCrewzWp_postmeta',
array(
'post_id' => $post_ID,
'meta_key' => '_yoast_wpseo_sitemap-include',
'meta_value' => 'always'
),
array(
'%d',
'%s',
'%s'
)
);
}
add_action( 'publish_custom-jobs', 'on_jobs_publish', 10, 1 );
Also, instead of working with the global $wp_query
and run the insert method, I think it would be better to user update_post_meta
function.
function on_jobs_publish( $post_ID ) {
update_post_meta($post_ID, '_yoast_wpseo_sitemap-include', 'always' );
}
add_action( 'publish_custom-jobs', 'on_jobs_publish', 10, 1 );
Note that publish_{post-type}
action is triggered when the post change the status from any value to “publish”. This mean that if the post is already published and you try to update it, this function won’t be executed. If you need to execute it without taking care of the post status, use save_post
action hook:
function on_jobs_publish( $post_ID, $post ) {
//Check that the post type being edited is our custom post type
if ( $post->post_type != 'custom-jobs' ) {
return;
}
update_post_meta($post_ID, '_yoast_wpseo_sitemap-include', 'always' );
}
add_action( 'save_post', 'on_jobs_publish', 10, 2 );
And one more advise for future. When you use wpdb
class, like you are using insert method, never use the full table name, instead replace the prefix with $wpdb->prefix
property. It is much safer. For example, in your code:
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'_postmeta',
//Rest of the code