What is an alternative method to the WordPress private _doing_it_wrong() function

What is an alternative method to the WordPress private _doing_it_wrong() function?

There’s no way that WordPress is ever going to get rid of the _doing_it_wrong() function, so it’s perfectly safe to use it. But if for some reason you don’t want to use it because it’s marked private, then you could create a plugin that has a function called doing_it_wrong() that is copy and pasted from _doing_it_wrong().

Another way would be to not copy code and instead use a class that handles deprecated code. Here’s some sample code that basically does the same thing as _doing_it_wrong().

class deprecated {
  protected $method;
  protected $message;
  protected $version;

  public function method( $method ) {
    $this->method = $method;
    return $this;
  }

  public function message( $message ) {
    $this->message = $message;
    return $this;
  }

  public function version( $version ) {
    $this->version = sprintf( 
      __( 'This message was added in version %1$s.' ), 
      $version
    );
    return $this;
  }

  public function trigger_error() {
    do_action( 'doing_it_wrong_run', $this->method, $this->message, $this->version );
    if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
      trigger_error( sprintf( 
        __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),
        isset( $this->method ) ? $this->method : '', 
        isset( $this->message ) ? $this->message : '', 
        isset( $this->version ) ? $this->version : ''
      ) );
    }
  }
}

Usage

class wpse_238672 {
  public function some_deprecated_method() {
    ( new deprecated() )
      ->method( __METHOD__ )
      ->message( __( 
        'Deprecated Method: Use non_deprecated_method() instead.', 'wpse-238672'
       ) )
      ->version( '2.3.4' )
      ->trigger_error();

    $this->non_deprecated_method();
  }

  public function non_deprecated_method() {
  }
}

Leave a Comment