0

I am creating a current vacancies feature in a client site, and am struggling on one area. I want to have a slug generated from a reference number, rather than the post title. This, I have set up. However, if a reference number is not entered, I want for Wordpress to generate a reference from dechex(time()). I then want for that generated reference to become the slug, but only if the meta field is empty.

Here is the code I have at the moment:

add_action('save_post', 'ocp_jobs_save_details');
function ocp_jobs_save_details(){
  global $post;
  update_post_meta($post->ID, "ocp_jobs_ref", $post->post_name);
  // Other update_post_meta functions for other meta fields
}

add_filter( 'wp_insert_post_data', 'ocp_jobs_slug' );
function ocp_jobs_slug( $data ) {
    if( 'job' == $data['post_type'] ) {
      if ( $_POST['ocp_jobs_ref'] ) { $data['post_name'] = sanitize_title( $_POST['ocp_jobs_ref'] ); }
      else { $data['post_name'] = sanitize_title( dechex( time() ) ); }
    } else { }
    return $data;
}

Up to now, I have the following:

  1. My dechex(time()) reference number is being generated.
  2. My generated number is being added to post_name.
  3. When posted / updated, the generated reference number is inserted into the meta field.

What isn't happening, however, is the ocp_jobs_ref reference is not taking priority over the dechex(time()) reference. The generated number should only be used if I don't enter a reference number manually. I gather that the wp_insert_post_data hook works before I even publish, so the reference number is generated and added automatically, rendering the submitted number redundant.

Any help?

0

Ok, after a little playtime, here is the answer:

add_action('save_post', 'ocp_jobs_save_details');
function ocp_jobs_save_details(){
  global $post;
  $genref = sanitize_title( dechex( time() ) );
  if ( $post->post_type == 'job' ) {
    if ( $_POST['ocp_jobs_ref'] ) { $jobs_args = array( 'ID' => $post->ID, 'post_name' => strtolower( sanitize_title( $_POST['ocp_jobs_ref'] ) ) ); $myref = strtoupper( $_POST['ocp_jobs_ref'] ); }
    else{ $jobs_args = array( 'ID' => $post->ID, 'post_name' => strtolower( $genref ) ); $myref = strtoupper( $genref ); }
    if ( ! wp_is_post_revision( $post->ID ) ){
        remove_action('save_post', 'ocp_jobs_save_details');
        wp_update_post( $jobs_args );
        add_action('save_post', 'ocp_jobs_save_details');
    }
  }
  update_post_meta($post->ID, "ocp_jobs_ref", $myref);
  // Other update_post_meta functions
}

The wp_insert_post_data filter isn't needed at all. It probably isn't pretty or elegant, but it works.

|improve this answer|||||

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.