Skip Navigation

[Resolved] How can I add a custom post to my WP site?

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

This topic contains 1 reply, has 2 voices.

Last updated by Christian Cox 2 months, 1 week ago.

Assigned support staff: Christian Cox.

Author
Posts
#1711767

Dear Sir/Madam,

Every time when a visitor visits my site, I want to add a custom post with a custom field, can I have the code to do that?

Best regards,

Kelvin.

#1711925

Christian Cox
Supporter

Languages: English (English )

Timezone: America/New_York (GMT-04:00)

I can provide a code snippet that will create a custom post and set a custom field value in that post, but I am not sure of the best way to trigger that code once per visit. The logic for determining "what is a visit" and "who is a visitor" is complex, and there are many factors to consider. It is not something Toolset is designed to accomplish, so there are no Toolset APIs related to "visit"s or "visitors".

To create a custom post and set a custom field value you can trigger code like this:

// Create a post object
$my_post = array(
  'post_title'    => 'The post title',
  'post_type'     => 'post-type-slug',
  'post_status'   => 'publish',
  'post_author'   => 1,
  'meta_input' => array(
    'wpcf-field-slug' => 'field value',
  )
);
 
// Insert the post into the database
wp_insert_post( $my_post );

If the custom field is created in Types, you must use the wpcf- prefix with the field slug from wp-admin. If the field is not created in Types, the wpcf- prefix is not required for the field slug.