WordPress comes with lots of handy functions and some of these functions arewp_insert_post() and wp_insert_comment() which has the power to add your data programmatically, in this article; I’ll show you how you can easily add posts and comments to your WordPress site.

To insert post

This snippet is use to insert post programmatically.
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
// Create post object
  $my_post = array(
     ‘post_title’ => ‘Your post title’,
     ‘post_content’ => ‘Your post content goes here’,
     ‘post_status’ => ‘publish’,
     ‘post_author’ => 1,
     ‘post_category’ => array( 8,39 )
  );
// Insert the post into the database
  wp_insert_post( $my_post );
?>
Note: The wp_insert_post() return the post ID if if the post is successfully added to the database. On failure, it returns 0 if $wp_error is set to false.

Syntax

PHP
1
<?php wp_insert_post( $post, $wp_error ); ?>

Parameters

  • post_title: The post title.
  • post_content: The content of the post
  • post_status: The post status (published, draft, etc.)
  • post_author: ID of the post author
  • post_type: Page, Post or Custom post type
  • post_category: Single category or an Array of category ID’s
If you wish to remove HTMLJavaScript, and PHP tags from the post_title and any other fields, you can use otherwordpress built-in function wp_strip_all_tags().
Update the above post title into this line of code
PHP
1
‘post_title’ => wp_strip_all_tags( ‘Your post title’ ),

To insert comment

This snippet use to inserts a comment to the database.
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
$time = current_time(‘mysql’);
$data = array(
    ’comment_post_ID’ => 1,
    ’comment_author’ => ‘admin’,
    ’comment_author_email’ => ‘admin@admin.com’,
    ’comment_author_url’ => ‘http://sutanaryan.com/’,
    ’comment_content’ => ‘Comment content goes here’,
    ’user_id’ => 1,
    ’comment_author_IP’ => ’127.0.0.1′,
    ’comment_agent’ => ‘Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)’,
    ’comment_date’ => $time,
    ’comment_approved’ => 1,
);
// Insert the comment into the database
wp_insert_comment($data);
?>
Note: The wp_insert_comment() return new commend ID if the comment is successfully added to the post/database.

Parameters

  • comment_post_ID: ID of the commented post
  • comment_author: Name of the comment author
  • comment_author_email: Email address of the comment author
  • comment_author_url: Website of the comment author
  • comment_content: Message of the comment
  • comment_author_IP: IP address of the comment author
  • comment_agent: User agent of the commenter browser
  • comment_date: Date of the comment
  • comment_date_gmt: GMT date of the comment
  • comment_approved: 1 for approve or 0 for “awaiting moderation”
That’s it, if you have suggestion, opinion use the comment below to share your idea.

0 comments:

Post a Comment

 
Top