1

Hey there for some reason I have a function which has to find posts by either ID, name or post title. It looks like this:

/**
 * @param $name_or_id: Name or ID of the post to find
 * @param $posttype: The Post Type
 * @return null|WP_Post
 */
function r2o_find_post($name_or_id,$posttype) {

    if(is_numeric($name_or_id)) {
        $id = abs(intval($name_or_id));
        if($id > 0) {
            $post = get_post($id);
            if(is_object($post) && $post->post_type == $posttype) {
                return $post;
            }
        }
        return null;
    }

    $slargs = array(
        'post_title'        => $name_or_id,
        'post_type'   => $posttype,
        'post_status' => 'publish',
        'numberposts' => 1
    );
    $pt = get_posts($slargs);

    if(is_array($pt)) {
        return $pt[0];
    }
    return null;
}

However in $slargs I can only do:

post_title => $name_or_id 
OR 
post_name => $name_or_id

Can I do this "OR"-relationship with WP_Query/get_posts without doing two seperate queries?

1 Answer 1

1

No. WP_Query class doesn't support OR based conditional query on same table's columns. So in this case you have to write your own SQL query. And as there is a query must to get this single post, it's not gonna hamper the performance. :)

However, I have re-write your code a slightly different way. This way you wouldn't need to use both get_post() and get_posts(). Only one get_posts() call would be enough. Here is this-

/**
 * @param $name_or_id: Name or ID of the post to find
 * @param $posttype: The Post Type
 * @return null|WP_Post
 */
function r2o_find_post( $name_or_id, $posttype ) {

    $slargs = array(
        'post_title'  => $name_or_id,
        'post_type'   => $posttype,
        'post_status' => 'publish',
        'posts_per_page' => 1,
    );

    if( is_numeric( $name_or_id ) ) {
        $id = abs( intval( $name_or_id ) );
        if( $id > 0 ) {
            unset( $slargs[ 'post_title' ] );
            $slargs['post__in'] = [ $name_or_id ];
        }
    }

    $pt = get_posts( $slargs );

    if( is_array($pt) ) {
        return $pt[0];
    }
    return null;
}

My main theory above there is, we are manipulating the arguments of get_posts() based on the type of name_or_id parameter.

Hope this above helps.

2
  • numberposts isn't 'deprecated'. It's just an alias for posts_per_page that makes more sense for get_posts(), which is not meant to be used for paginated content (and in fact sets no_found_rows to true automatically). Commented Feb 28, 2018 at 16:04
  • Uha.... I see. I didn't know that. :) Thanks ! @JacobPeattie
    – CodeMascot
    Commented Feb 28, 2018 at 16:28

Your Answer

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

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