1

I've made a site, where there's a category for each page. And now I'm trying to make it so, that if you on that given page press 'Create post', that it then sends a parameter to the URL, as such:

example.org/wp-admin/post-new.php?post_type=CPT&category=3

And it doesn't need to actually put the post in the category... It just needs to set the checkmark in the category with ID=3, so when it's posted, that it then does it then.

I imagined hooking onto something along the lines of 'create_post' or something like that and just do it with some JavaScript (find #categorydiv and .inside, and find the category by ID and mark it as checked). But it feels a bit 'hacky' to me.

Is it really the right way to do it, - or does WordPress offer a better way?

1 Answer 1

0

I figured it out myself, but by using several different small things. I'm sorry to 'steal the credit', - but I can't remember all the sources used:

This is the JavaScript:

jQuery(document).ready(function() {

  function GetURLParameter(sParam) { 
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
      var sParameterName = sURLVariables[i].split('=');
      if (sParameterName[0] == sParam) {
        return sParameterName[1];
      } // Endif
    } // Endfor
  } // Endfor

  var just_the_category_ID = GetURLParameter('category'); // Get the category-parameter from the URL
  jQuery('#in-category-' + just_the_category_ID ).prop('checked', true);
});

And it it called with this function in functions.php:

function custom_enqueue_admin_scripts(  ) {

  global $page_category_mapping;
  $screen = get_current_screen(); // Which page we're on

  if ( in_array( $screen->id, array( 'page' ) ) && $screen->action == 'add' ) {
    wp_enqueue_script( 'mark-default-category', get_stylesheet_directory_uri() . '/assets/js/THE-LOCATION-OF-THE-JS-FROM-ABOV.js', array( 'jquery' ) );
  }
}
add_action( 'admin_footer', 'mss_enqueue_admin_scripts' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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