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;  
    $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 );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try to use function sanitize_title()documentation, which converts a string into a slug when you check if it is already in the permalink, and when appending it to permalink:

function custom_job_post_type_link( $post_id, $post ) {

    $permalink = $post->post_name;  
    $companyname = $post->_company_name;

    if ( strpos( $permalink, sanitize_title($companyname) ) ) { // <-- Here
        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 .= '-' . sanitize_title($companyname); // <-- And here

    // 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 );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x