Create Post Query to order by a Taxonomy custom meta field

I have a standard WP_Query to search for Posts of a certain Custom Post Type. I am trying to extend this by filtering by a specific custom meta field that was set for a Taxonomy that is attached to the Post.

What I’ve done is created a Taxonomy, and in that Tax I’ve added a custom meta field called “sorting_weight” that is a numerical field. So when admin assign a CPT to this Tax, I would be able to query all CPT entries and then orderly that numerical field.

All the tutorials online are getting confused and thinking the user wants to sort by normal post custom meta. This is not what I want – I want to sort by the CPT’s Taxonomy’s custom meta.

From what I can gather, I can’t even pipe this logic into a normal WP_Query argument? If so, how would I refactor my code to order by this Taxonomy custom meta field “sorting_weight”?

The below shows the general query I am using:

     /**      * @return array      */     protected function returnQuery(): array     {         $  query = [             'post_type' => $  this->getPostTypeName(),             'show_posts' => -1,             'hide_empty' =>  true,             'meta_key' => 'year',             'orderby' => 'meta_value',             'order' => 'DESC'         ];          /**          * CPT Meta Queries          */         if ($  this->getSearchQuery()['appGallerySearch_Category']) {             $  query['meta_query'][] = [                 'key' => 'topic',                 'value' => $  this->getSearchQuery()['appGallerySearch_Category'],                 'compare' => 'LIKE'             ];         }         if ($  this->getSearchQuery()['appGallerySearch_Program']) {             $  query['meta_query'][] = [                 'key' => 'program',                 'value' => $  this->getSearchQuery()['appGallerySearch_Program'],                 'compare' => 'LIKE'             ];         }         if ($  this->getSearchQuery()['appGallerySearch_Division']) {             $  query['meta_query'][] = [                 'key' => 'divisions',                 'value' => $  this->getSearchQuery()['appGallerySearch_Division'],                 'compare' => 'LIKE'             ];         }         if ($  this->getSearchQuery()['appGallerySearch_Year']) {             $  query['meta_query'][] = [                 'key' => 'year',                 'value' => $  this->getSearchQuery()['appGallerySearch_Year'],                 'compare' => 'LIKE'             ];         }         if ($  this->getSearchQuery()['appGallerySearch_Location']) {             $  query['meta_query'][] = [                 'key' => 'region',                 'value' => $  this->getSearchQuery()['appGallerySearch_Location'],                 'compare' => 'LIKE'             ];         }         if ($  this->getSearchQuery()['appGallerySearch_Keyword']) {             $  query['meta_query'][] = [                 'key' => 'description',                 'value' => $  this->getSearchQuery()['appGallerySearch_Keyword'],                 'compare' => 'LIKE'             ];         }          return $  query;     } 

DnD 5e stealth check, meta game and overpowered stealth hide out of combat

Recently I’ve faced with the following situation and was really surprised with the rules:

Let’s consider the following situation: A party is located in a quite deep forest. They know that there is an enemy camp within 1 mile away also located in deep forest. One player says: “I’m trying to hide”.

In PHB DnD 5e it is explicitly stated (PHB p.177)

When you try to hide, make a Dexterity (Stealth) check. Until you are discovered or you stop hiding …

So he makes a roll and let’s assume the final result is 4. Because player can see the result, he can now decide what he is going to do based on this check. Obviously this check is low, and player says: “I stop hiding”. It is allowed based on the cite above. After that he can try to hide again and re-roll.

In this case DM can notice that this is a meta game and it is not allowed, because character can’t know the roll. In this case, even if this will prevent character from re-rolling directly, it can certainly change his initial plan. Or player can do the following:

Character can make an agreement with his party that he will go behind a tree, hide and then they will try to seek him. In this case it is explicitly mentioned in PHB p. 177 that

Until you are discovered or you stop hiding, that check’s total is contested by the Wisdom (Perception) check of any creature that actively searches for signs of your presence. … When you hide, there’s a chance someone will notice you even if they aren’t searching. To determine whether such a creature notices you, the DM compares your Dexterity (Stealth) check with that creature’s passive Wisdom (Perception) score

So even if character doesn’t know the roll, he can find “how well he hides” with this “test”. This “test” can be made using both passive and active checks. In this case he can definitely find “how good he hides”. If somebody in his party could spot him, character is no longer hidden, because that rule above, if not, character is very likely hidden very well (especially if there was a wisdom guy in a party that was by accident unaware of this activity and the check was passive e. g. with fixed known high value). So if character was spotted he just reties to hide until he rolls high enough to hide from his party checks.

So at this moment our hero is hiding and has a really high roll. So he says that he is travelling towards enemies camp in hiding.

Here are rules from PHB p. 182

While traveling at a slow pace. the characters can move stealthily. As long as they’re not in the open, they can try to surprise or sneak by other creatures they encounter. See the rules for hiding in chapter 7.

The “chapter 7” rule are the one I mentioned above.

Well, since our hero is hiding and he travels in slow pace, he comes to enemy camp and he is still hidden because he “was not yet discovered” (see cite 2 above).

After that hero says “I try to sneak by those creatures remaining hidden”. So since they are not expecting him, they use passive check. Since player already rolled high and that roll value is used against perception checks there is no chance they can spot him, so he automatically (or with very high chance) succeed. In this way he can bypass any guards almost guaranteed.

The same trick can be made with whole party by searching each other and repeating until all are hidden and thus it can be made that surprise is be also guaranteed in first round.

For me it looks like it is 100% correct according to the rules from PHB and it also it looks like extremely broken mechanics. No other check value is known to player before he decides what is he going to do with this ability.

So, eventually:

Is there any fix for this rules published somewhere?

P. S. I think any check should be made at the moment the check is really needed and each moment it should be checked independently.

So in this case you don’t roll when you trying to hide. You roll each time you can be spotted, also you roll on each action you perform, e. g. sneak by e. t. c. because all other checks are performed in the same way. Again even if you somehow block a party from doing that, player won’t try to sneak by a group of goblins when he knows ahead that his roll value is low and already determined.

P. P. S. I’ve also checked several forums and videos and everywhere it is explicitly stated that you make check when you hide and you use this single value to compete perception checks and you remain hidden until you found or you stop hiding. Also everywhere it stated that you can move and sneak while hidden and use that roll value against perception checks. So I am really confused.

Update post meta not working in transition_post_status

I am developing a plugin for custom post type which take the link from the title of the post and then after scraping on that link it updates all things like post title, post permalink and post_meta. Now its only updating the title and the link but not the post meta, I have tried debugging the data.

function a_new_post($  new_status, $  old_status, $  post) {      if ('publish' !== $  new_status or 'publish' === $  old_status)         return;     $  new_slug = sanitize_title($  post->post_title);     if ('aps-products' !== $  post->post_type)         return; // restrict the filter to a specific post type      $  result= getSpecs($  post->post_title);  /* ****************************************************************************** ****************************************************************************** ****************************************************************************** */ $  groups = get_aps_cat_groups(16); $  groups_data = get_aps_groups_data(); $  attrs_data = get_aps_attributes_data();  // get aps attributes data from input fields  foreach ($  groups as $  groupId) {     $  group_data = $  groups_data[$  groupId];     $  group_values = get_aps_product_attributes($  post->ID, $  groupId);      if ($  group_data['attrs']) {         if (aps_is_array($  group_data['attrs'])) {             $  first=array();             $  value='';             foreach ($  group_data['attrs'] as $  attr_id) {                 switch($  attr_id){                     case 20:                         $  value=$  result[1];                     break;                     case 21:                         $  value=$  result[12];                     break;                     case 22:                         $  value=$  result[3];                     break;                     case 24:                         $  value=$  result[13];                     break;                 }                 $  frist[$  attr_id]=$  value;             }             update_post_meta( $  post->ID, 'aps-attr-group-' .$  groupId, $  first );         }     } }    /* ****************************************************************************** ****************************************************************************** ****************************************************************************** */      $  post_update = array(         'ID'         => $  post->ID,         'post_title' => $  result[0].' '.$  result[1]     );     if (!wp_is_post_revision($  post->ID)) {         wp_update_post($  post_update);         $  new_slug = sanitize_title($  result[0].' '.$  result[1]);         if ($  post->post_name != $  new_slug) {             wp_update_post(                 array(                     'ID'        => $  post->ID,                     'post_name' => $  new_slug                  )             );         }     } } 

change the dropdown content of author post meta in edit post – admin

I am trying to customize the author meta box in the post edit page, as you all know this dropdown is using to assign a post to a corresponding author.

I would like to change the dropdown content. Like currently, its showing display name(username). But i would like to show a user meta field rather than username. Is it possible?

So in the dropdown it will be like Display name(custom user meta field).

I have seen wp_dropdown_users, but no idea how to use it so that i can achieve.

How to register meta field with checkbox to REST API with default value true?

I have a meta field with checkbox, it has by default checked value, but when I register it to REST API my checkbox become unchecked.

How can I get it checked by default?

Here is my code for metabox:

function modest_gutenberg_meta_add_meta_box() {     $  post_types = array('post', 'page', 'modest_portfolio');     foreach ($  post_types as $  post_type) {         add_meta_box(              'modest_gutenberg_meta_post_title_option',              esc_html__( 'Title Options', 'modest-gutenberg-meta' ),              'modest_gutenberg_meta_post_title_settings',              $  post_type,              'normal',              'high',              array('__back_compat_meta_box' => true));     } }  add_action( 'add_meta_boxes', 'modest_gutenberg_meta_add_meta_box' );  function modest_gutenberg_meta_post_title_settings($  post) {     $  visibility_title = get_post_meta($  post->ID, '_modest_gutenberg_meta_post_title_visibility', true);     $  checked_title = 'checked';     if($  visibility_title == 'unchecked' && !empty($  visibility_title)) {            $  checked_title = '';     }      wp_nonce_field( 'modest_gutenberg_meta_update_post_title_settings', 'modest_gutenberg_meta_update_post_title_nonce' );     ?>          <input type="checkbox" name="modest_gutenberg_meta_post_title_visibility_field" id="modest_gutenberg_meta_post_title_visibility_field" value="1" <?php echo $  checked_title; ?> />             <label for="modest_gutenberg_meta_post_title_visibility_field"><?php esc_html_e( 'Display Title', 'modest-gutenberg-meta' ); ?></label>      <?php }  function modest_gutenberg_meta_save_post_title_settings($  post_id, $  post) {      $  edit_cap = get_post_type_object( $  post->post_type )->cap->edit_post;     if( !current_user_can( $  edit_cap, $  post_id )) {         return;     }     if( !isset( $  _POST['modest_gutenberg_meta_update_post_title_nonce']) || !wp_verify_nonce( $  _POST['modest_gutenberg_meta_update_post_title_nonce'], 'modest_gutenberg_meta_update_post_title_settings' )) {         return;     }     if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {         return;     }      if(array_key_exists('modest_gutenberg_meta_post_title_visibility_field', $  _POST)) {         update_post_meta(              $  post_id,              '_modest_gutenberg_meta_post_title_visibility',              sanitize_text_field($  _POST['modest_gutenberg_meta_post_title_visibility_field'])         );     } else {         update_post_meta(              $  post_id,              '_modest_gutenberg_meta_post_title_visibility', 'unchecked');     } } 

And then I register_meta:

function modest_gutenberg_meta_register_meta() {     //title     register_meta( 'post', '_modest_gutenberg_meta_post_title_visibility', array(         'show_in_rest' => true,         'type' => 'boolean',         'single' => true,         'sanitize_callback' => 'sanitize_text_field',         'auth_callback' => function() {             return current_user_can( 'edit_posts' );         }     ) ); }  add_action('init', 'modest_gutenberg_meta_register_meta'); 

I’m registering meta for Gutenberg Plugin to add a new Sidebar, there I have ToggleControl, which make my meta update and it’s working.

But I can’t understand what am I doing wrong with default value?

How can I get my value checked by default inside WordPress REST API?

If I delete register_meta() function and switch inside add_meta_box() __back_compat_meta_box to false and refresh the page which I’m editing,

I will get my checkbox true and then if I register_meta() again and refresh page I will get my meta in REST API checked.

Sorry for my English, hope someone can help me)

Thanks in advance.

Disable Fields in Custom Meta Boxes inside Custom Post Type

I want to create an Options page for my plugin.

I have two custom post types. Both habe metaboxes with fields inside. They are perfectly saving now (thanks to you guys on stackexchange).

Now, I want to create an Options Page (already done) and want to allow the admin to disable or enable every single field of every metabox

For example

Post Type: np-food Metabox: nutrition-info fields: energy_kcal, energy_kilojoule, etc


Enable energy_kcal yes/no dropdown Enable energy_kilojoule yes/no dropdown

Saving removes them if disabled and let them appear if enabled.

Glad for any help 🙂

Have a great Day


Custom Meta Box (SELECT2) Not Saving Taxonomy Terms

I have the code, enter image description here

/*  * Add a metabox  * I hope you're familiar with add_meta_box() function, so, nothing new for you here  */ add_action( 'admin_menu', 'rudr_metabox_for_select2_cat' ); function rudr_metabox_for_select2_cat() {     add_meta_box( 'rudr_select2', 'Tune Category', 'rudr_display_select2_cat_metabox', 'post', 'side', 'high' ); } /*  * Display the fields inside it  */ function rudr_display_select2_cat_metabox( $  post_object ) {     // I decided to write all the metabox html into a variable and then echo it at the end     $  html = '';      // always array because we have added [] to our <select> name attribute     $  appended_cat = get_post_meta( $  post_object->ID, 'rudr_select2_cat',true );      /*      * It will be just a multiple select for tags without AJAX search      * If no tags found - do not display anything      * hide_empty=0 means to show tags not attached to any posts      */     if( $  cats = get_terms( 'category', 'hide_empty=0' ) ) {         $  html .= '<p><select id="rudr_select2_cat" name="rudr_select2_cat[]" single="single" style="width:99%;max-width:25em;">';         foreach( $  cats as $  cat ) {             $  selected = ( is_array( $  appended_cat ) && in_array( $  cat->term_id, $  appended_cat ) ) ? ' selected="selected"' : '';             $  html .= '<option value="' . $  cat->term_id . '"' . $  selected . '>' . $  cat->name . '</option>';         }         $  html .= '<select></p>';     }     echo $  html; } add_action( 'wp_ajax_mishagetcat', 'rudr_get_cat_ajax_callback' ); // wp_ajax_{action} function rudr_get_cat_ajax_callback(){      // we will pass post IDs and titles to this array     $  return = array();      $  cat = get_terms( array('taxonomy' => 'category','search'=> $  _GET['q'],'ignore_sticky_posts' => 1,));         foreach ( $  cat as $  cat ) {               // shorten the title a little             $  title = ( mb_strlen( $  cat->name ) > 50 ) ? mb_substr( $  cat->name, 0, 49 ) . '...' : $  cat->name;             $  return[] = array( $  cat->term_id, $  title ); // array( Post ID, Post Title )         }     echo json_encode( $  return );     die; } //auto_save add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 ); function rudr_save_metaboxdata( $  post_id, $  post ) {      if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $  post_id;      // if post type is different from our selected one, do nothing     if ( $  post->post_type == 'post' ) {         if( isset( $  _POST['rudr_select2_cat'] ) )             update_post_meta( $  post_id, 'rudr_select2_cat', $  _POST['rudr_select2_cat'] );         else             delete_post_meta( $  post_id, 'rudr_select2_cat' );         if( isset( $  _POST['rudr_select2_tags'] ) )             update_post_meta( $  post_id, 'rudr_select2_tags', $  _POST['rudr_select2_tags'] );         else             delete_post_meta( $  post_id, 'rudr_select2_tags' );     }     return $  post_id; } //add_script_&_stylesheet add_action( 'admin_enqueue_scripts', 'rudr_select2_enqueue' ); function rudr_select2_enqueue(){      wp_enqueue_style('select2', '' );     wp_enqueue_script('select2', '', array('jquery') );      // please create also an empty JS file in your theme directory and include it too     wp_enqueue_script('mycustom', get_template_directory_uri() . '/css/mycustom.js', array( 'jquery', 'select2' ) );   } 

enter image description here But Showing only deafult category.

WordPress hook after post content and meta update

I want to update one of my meta field and redirect and I am using post_updatedhook. Here is my code.

function job_publish_status( $  post_ID, $  post_after, $  post_before ) {    $  job_published_date = get_the_time("Y-m-d", $  post_ID);    $  expire_date = date('Y-m-d', strtotime($  job_published_date. ' + 60 days'));    update_post_meta($  post_ID, '_job_expires', $  expire_date);    $  url = get_site_url();    $  url = $  url.'/wp-admin/post.php?post='.$  post_ID.'&action=edit';    wp_redirect( $  url );    exit;  } add_action('post_updated', 'job_publish_status', 99, 3 ); 

It is updating this _job_expires meta field and redirecting correctly. When I edit post content and title, its updates title and content but it is not updating other meta fields in this post. Is there any hook which triggers after post content update and meta fields update ?