Make WordPress Core

#55877 closed defect (bug) (fixed)

wp_insert_post() should check that a post type exists before using it

Reported by: chouby's profile Chouby Owned by: sergeybiryukov's profile SergeyBiryukov
Milestone: 6.1 Priority: normal
Severity: normal Version: 5.1
Component: Posts, Post Types Keywords: has-patch needs-unit-tests
Focuses: Cc:

Description

In #27335 it was accepted that wp_insert_post() can insert a post from an unknown post type - although not consistent with wp_insert_term() which returns a WP_Error for an invalid taxonomy but that's another issue.

Later, 42380 introduced some usage of the post type object inside wp_insert_post(), still without checking that the post type exists.

Thus writing a test including:

<?php
$args = array(
        'post_title'  => 'My post',
        'post_type'   => 'unregistered',
        'post_status' => 'pending'
)
$post_id = wp_insert_post( $args );

will fire the error Trying to get property 'cap' of non-object.

Attachments (1)

55877.patch (729 bytes) - added by Chouby 12 months ago.

Download all attachments as: .zip

Change History (6)

@Chouby
12 months ago

#1 @Chouby
12 months ago

  • Keywords has-patch added

The proposed patch fixes the PHP error still maintaining the possibility to insert post of invalid post types.

#2 @SergeyBiryukov
12 months ago

  • Keywords needs-unit-tests added
  • Milestone changed from Awaiting Review to 6.1

#3 @mukesh27
12 months ago

Hi there!

I reproduced the issue fresh WordPress with the 6.1-alpha-53451 version and it is one additional warning.

PHP Warning: Attempt to read property "publish_posts" on null in wp-includes\post.php on line 4158

After the 55877.patch patch it will now show any error in log.

#4 @rafiahmedd
12 months ago

@mukesh27 it looks good. I just have a suggestion here, I think it will be good if we make our if condition like this

if (  ! empty( $post_type_object )  && ! $update && 'pending' === $post_status && ! current_user_can( $post_type_object->cap->publish_posts ) )

As we are checking the $post_type_object first so whenever it will be null then it won't go to the second condition and it will save some time.

Thanks

Last edited 12 months ago by rafiahmedd (previous) (diff)

#5 @SergeyBiryukov
10 months ago

  • Owner set to SergeyBiryukov
  • Resolution set to fixed
  • Status changed from new to closed

In 53771:

Posts, Post Types: Check if the post type exists in wp_insert_post().

This avoids an Attempt to read property "cap" on null PHP warning when checking an unregistered post type's publish_posts capability to disallow contributors setting the post slug for pending posts.

Follow-up to [9055], [42380].

Props Chouby, mukesh27, rafiahmedd, SergeyBiryukov.
Fixes #55877.

Note: See TracTickets for help on using tickets.