Skip to content
Snippets Groups Projects

NullObject - 1

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Krzysztof Dyszczyk
    Edited
    null-value.php 734 B
    class WPDesk_Post_Not_Exists_Exception extends \Exception {
    }
    
    /**
     * @return \WP_Post
     * @throws \WPDesk_Post_Not_Exists_Exception
     */
    function get_wpdesk_post() {
        $post = get_post(123);
        if ($post) {
            return $post;
        }
    
        throw new WPDesk_Post_Not_Exists_Exception('WPDesk post 123 is not available in the database');
    }
    
    /**
     * @return string When post not exists returns default post title.
     */
    function get_wpdesk_post_title() {
        try {
          return get_wpdesk_post()->post_title;
        } catch (\WPDesk_Post_Not_Exists_Exception $not_exists) {
          return __('Some placeholder title', 'some-text-domain');
        }
    }
    
    function display_wpdesk_title() {
        echo get_wpdesk_post_title();
    }
    
    display_wpdesk_title();
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment