Using (array() in custom conditional functions

How can I create an array of multiple endpoint for the below custom conditional code?

function is_single_with_endpoint( $endpoint ) {
global $wp_query;
   if ( ! isset( $endpoint ) && ! empty( $endpoint ) ) {
       return false;
   }
   if ( array_key_exists( $endpoint, $wp_query->query_vars ) ) {
       return true;
   } else {
       return false;
   }
}

This will work is I use

if ( ! is_single_with_endpoint('overview') && ! is_single_with_endpoint('analytics') ) {

but not as

if ( ! is_single_with_endpoint(array('overview','analytics')) ){

2 answers

  • answered 2018-02-13 00:56 sorak

    We can just step through the array of inputs and check each one for a failure. If none of them produce failure, then it passes at the end.

    function is_single_with_endpoint($endpoints) {
        global $wp_query;
    
        // Iterate through set (can be set of one)
        foreach ((array)$endpoints AS $endpoint) {
            if (empty($endpoint)) {
                return false;
            }
            if (!array_key_exists($endpoint, $wp_query->query_vars)) {
                return false;
            }
        }
    
        // Didn't fail, so it passes
        return true;
    }
    

  • answered 2018-02-13 01:08 PHPglue

    I would do this, instead:

    function is_single_with_endpoint($endpoint = null){
      global $wp_query;
      if($endpoint === null){
        return false;
      }
      if(is_array($endpoint)){
        foreach($endpoint as $k => $v){
          if(!array_key_exists($k, $wp_query->query_vars)){
            return false;
          }
        }
      }
      else{
        if(!array_key_exists($endpoint)){
          return false;
        }
      }
      return true;
    }