• IoClaudio

    (@ioclaudio)


    Hi,

    I noticed a strange behaviour of the function get_posts. I’ve defined a custom post type called “evento” that seems to work correctly. However using this array as parameter:

    $args
    array(3)
    post_name:
    "turbulence-on-the-banks"
    post_type:
    "evento"
    numberposts:
    1

    When I execute the following code to check if a post exists by slug it returns the wrong item:

    
    $args = array(
    	'post_name'   => $slug,
    	'post_type'   => $content_type,
    	'numberposts' => 1,
    );
    $posts = get_posts( $args );
    
    $posts[0]['post_type']
    "evento"
    $posts[0]['post_name']
    "giornata-della-solidarieta-2024"
    
    

    How is it possible?

    In this case the post doesn’t exist and I expect an empty array.

    I’m using WordPress 6.5.3.

    Thank you very much.

    Claudio

Viewing 3 replies - 1 through 3 (of 3 total)
  • Tridhya Tech Limited

    (@tridhyatechltd)

    Hello @ioclaudio ,
    I hope you are doing well,
    I just checked your code and can you please give me more brief information on how you can data in the defined variable also give us full code so we can understand where you made a mistake or where the code is breaking.

    Thread Starter IoClaudio

    (@ioclaudio)

    Hi,

    this is the full function I’m using:

    if( ! function_exists( 'dli_get_content' ) ) {
    	function dli_get_content( $slug, $content_type ) {
    		$args = array(
    			'post_name'   => $slug,
    			'post_type'   => $content_type,
    			'numberposts' => 1,
    		);
    		$posts = get_posts( $args );
    		return $posts ? $posts[0] : null;
    	}
    }

    I call this function in this way:

    $page_check = dli_get_content( $post_name, EVENT_POST_TYPE );

    It doesn’t work either using ‘name’ or ‘post_name’ as parameter of the array.

    Sorry, I don’t understand what do you need exactly.

    Claudio

    • This reply was modified 2 years ago by IoClaudio.
    • This reply was modified 2 years ago by IoClaudio.
    Thread Starter IoClaudio

    (@ioclaudio)

    It seems that this instead works:

    if( ! function_exists( 'dli_get_content' ) ) {
    	function dli_get_content( $slug, $content_type ) {
    		$args = array(
    			'name'        => $slug,
    			'post_type'   => $content_type,
    			'post_status' => array( 'publish', 'draft' ),
    			'numberposts' => 1,
    		);
    		$posts = get_posts( $args );
    		return $posts ? $posts[0] : null;
    	}
    }

    You have to pass post_status, but I remember that before this code was working also without passing this parameter.

    However it is not right that it returns the first object when it doesn’t find anything. Probably this is a bug.

    Claudio

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Why the function get_posts returns the wrong post?’ is closed to new replies.