通过以下方式this howto, 我想以编程方式每天创建一篇帖子。根据作者的意见,下一行将检查是否已经存在具有给定名称的帖子:
if( null == get_page_by_title( $title ) ) {
// Create the page
} else {
// The page exists
} // end if
但这不起作用,因为我的WP生成了多个标题相同的帖子,因为我将该函数添加到了
函数中。php。Wordpress抄本
says 那个
get_page_by_title()
:
检索给定标题的帖子。如果有多篇文章使用相同的标题,则返回ID最小的文章。
因此,如果我正确理解get_page_by_title( $title )
不可能是null
. 这里怎么了?
我使用的完整代码:
/**
* A function used to programmatically create a post in WordPress. The slug, author ID, and title
* are defined within the context of the function.
*
* @returns -1 if the post was never created, -2 if a post with the same title exists, or the ID
* of the post if successful.
*/
function programmatically_create_post() {
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
// Setup the author, slug, and title for the post
$author_id = 1;
$slug = \'digest-\' . date( \'d-m-Y\', strtotime( "-1 days" ) );
$title = \'Digest - \' . date( \'d-m-Y\', strtotime( "-1 days" ) );
// If the page doesn\'t already exist, then create it
if( null == get_page_by_title( $title ) ) {
// Set the post ID so that we know the post was created successfully
$post_id = wp_insert_post(
array(
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
\'post_author\' => $author_id,
\'post_name\' => $slug,
\'post_title\' => $title,
\'post_status\' => \'pending\',
\'post_type\' => \'post\'
)
);
// Otherwise, we\'ll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
} // end if
} // end programmatically_create_post
add_filter( \'after_setup_theme\', \'programmatically_create_post\' );
最合适的回答,由SO网友:czerspalace 整理而成
如果您查看文档get_page_by_title
, 第三个参数是$post_type, Default: page
. 因为您正在创建帖子,所以应该传入post
调用get\\u page\\u by\\u title时作为帖子类型,如下所示:
if( null == get_page_by_title( $title, OBJECT, \'post\' ) )