Adding a custom field to a slug
I’m using the WP Job Manager plugin, and want to add the company name field to the slug automatically when I save a post.
I’ve got it working using the code below, but once I save and then edit the post again, it will re-add the company name, so job-title-company-name becomes job-title-company-name-company-name
Does anyone know what I’m doing wrong? I think there might be an issue with my IF statement which should check if the companyname string already exists in the slug, and if so, unhook the function.
function custom_job_post_type_link( $post_id, $post ) {
$permalink = $post->post_name;
$post->_company_name;
$companyname = $post->_company_name;
if ( strpos( $permalink, strval($companyname) ) ) {
return;
}
// unhook this function to prevent infinite looping
remove_action( 'save_post_job_listing', 'custom_job_post_type_link', 10, 2 );
// add the id to the slug
$permalink .= '-' . $companyname;
// update the post slug
wp_update_post( array(
'ID' => $post_id,
'post_name' => $permalink
));
// re-hook this function
add_action( 'save_post_job_listing', 'custom_job_post_type_link', 10, 2 );
}
add_action( ‘save_post_job_listing’, ‘custom_job_post_type_link’, 10, 2 );
Leave an answer
You must login or register to add a new answer .