• Hi there,

    trying to use custom fields to set Post Title and Slug.

    I have three custom fields;
    – Year
    – Number
    – Type

    And when a Custom Post is saved, I want to use these three custom fields (they are required fields) to set the title;
    – type – Year – Number

    Custom Post and Custom Fields ahve been generated by Toolset by WP Types.

    I have the following code in post.php when in functions.php, WP stops working all toghether. But for now, even in post.php it doesn’t work.

    function set_issue_title( $data , $postarr ) {
      if($data['post_type'] == 'Issue') {
        $issue_number = get_post_meta($postarr['ID'],'wpcf[number]',true);
        $issue_type = get_post_meta($postarr['ID'], 'wpcf[type]' , true);
        $issue_year = get_post_meta($postarr['ID'], 'wpcf[year]' , true);
        $issue_title = $issue_type . ' - ' . $issue_year . ' - ' . $issue_number;
        $post_slug = sanitize_title_with_dashes ($issue_title,'','save');
        $post_slugsan = sanitize_title($post_slug);
    
        $data['post_title'] = $issue_title;
        $data['post_name'] = $post_slugsan;
      }
      return $data;
    }
    add_filter( 'wp_insert_post_data' , 'set_issue_title' , '99', 3 );

    Any suggestions on whether the above code is correct and whether the location is an issue.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    If you mean the post.php in wp-admin or wp-includes, then no, that is the wrong place, never alter core code! If post.php is some sort of theme template, then it might be OK, but functions.php is the proper location. If the code does not work there, then there is a problem with the code, not the location.

    Not only should you never alter core code, but it’s inadvisable to edit theme code as well. You will lose your edits when the theme is updated. To protect your custom code, you should create a child theme.

    One reason your code is not working is you are adding the filter callback by specifying 3 parameters should be passed, but there are only 2 for this filter. Change the 3 to a 2 and put the code in functions.php of a child theme. If you still have trouble let me know and I’ll dig deeper.

Viewing 1 replies (of 1 total)

The topic ‘Set Post Title and Slug using Custom Fields’ is closed to new replies.