grazdev
grazdev

Reputation: 1272

OOP PHP method doesn't work when invoked within another method

I'm creating a PHP class for a Wordpress site. The following method works fine, but when I try to abstract it a bit by passing an argument and calling it within another method (see code further down below), it doesn't work anymore.

public function user_has_submitted_in_dog_category() {

    $args = array(
        'post_type' => 'submissions',
        'author' => get_current_user_id(),
        'tax_query' => array(
            array(
                'taxonomy' => 'submissions_categories',
                'field' => 'slug',
                'terms' => 'dog'
            )
        )
    );

    $user_posts = get_posts( $args );

    if( count( $user_posts ) )
        return true;

}

This is not working:

public function user_has_submitted_in_dog_category() {

    $this->user_has_submitted_in_animal_category( 'dog' );

}

public function user_has_submitted_in_animal_category( $category ) {

    $args = array(
        'post_type' => 'submissions',
        'author' => get_current_user_id(),
        'tax_query' => array(
            array(
                'taxonomy' => 'submissions_categories',
                'field' => 'slug',
                'terms' => $category
            )
        )
    );

    $user_posts = get_posts( $args );

    if( count( $user_posts ) )
        return true;

}

By not working, I mean that user_has_submitted_in_dog_category() is not returning true. I call it in a template file as follows:

<?php if( $submission->user_has_submitted_in_dog_category() ) : ?>
    <div class="msg">You have already submitted.</div>
<?php else : ?>
    <div class="msg">You have not submitted yet.</div>
<?php endif; ?>

The block of code prints You have not submitted yet, but I do have posts in my custom taxonomy dog.

Upvotes: 2

Views: 55

Answers (2)

Ollie in PGH
Ollie in PGH

Reputation: 2629

You need to return from your first (dog) method.

public function user_has_submitted_in_dog_category() {

    return $this->user_has_submitted_in_animal_category( 'dog' );

}

Upvotes: 1

Leon Aves
Leon Aves

Reputation: 779

Wordpress might be calling the method statically. You might be best off doing that yourself as the method doesn't seem to need an object instance to work:

public function user_has_submitted_in_dog_category() {

  MyClass::user_has_submitted_in_animal_category( 'dog' );

}

Upvotes: 0

Related Questions