0

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

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 );
| improve this answer | |
  • Thanks geouser! I just needed sanitize_title in the IF statement and now it works :) – michael74 Oct 3 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.