0

I'm trying to add an author filter to the WP Admin pages for the CPTs 'booking' and 'ticket' The code below works when using only one post type, but adding || and the second cpt stops it. I've tried an array but can't be writing that correctly either.

add_action( 'restrict_manage_posts', 'filter_author' );

function filter_author( $post_type ) {
    
    if( 'booking' || 'ticket' !== $post_type ) {
    return;
    }
    
    $selected = isset( $_GET[ 'user' ] ) && $_GET[ 'user' ] ? $_GET[ 'user' ] : '';
 
    wp_dropdown_users(
        array(
            'role__in' => array( 
                'administrator', 
                'editor', 
                'author',
                'contributor',
                'subscriber'
            ),
            'name' => 'author',
            'show_option_all' => 'All authors',
            'selected' => $selected
        )
    ); 
}

1 Answer 1

0

This isn't a WordPress problem, it's a programming logic mistake in this if statement:

if( 'booking' || 'ticket' !== $post_type ) {

This code is the same as this:

if( ( 'booking' != false ) ||  ( 'ticket' !== $post_type ) ) {

Which in plain language is:

If "booking" is a truthy value, or the $post_type variable is not 'ticket', then this if statement is true

If you want to compare a variable to multiple strings, you need to do multiple comparisons, you can't write something like this:

if ( $variable != A || B || C ) { // ❌

This might work when speaking to a human because that's how people might speak it out loud, but this isn't a sentence of language, it's boolean logic.

You also can't do this:

if ( $variable != [ A, B, C ] ) { // ❌

Because this isn't asking if variable is one of those values, it's asking if variable isn't that array!

Remember that computers and code are extremely literal, you can't imply things and hope it figures it out because there is no figuring out step. What you need this:

if ( $variable !=== A && $variable !=== B && $variable !===  C ) { // ✅

Or, to put the values in an array/list and ask if the value appears inside that array:

$unwanted = [ A, B, C, D ];
if ( in_array( $variable, $unwanted ) ) { // ✅
    // the variable appears inside the array/list
1
  • 1
    Thank yout very much - I've solved it with an array.
    – Blakar1988
    Oct 16 at 10:39

Your Answer

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

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