Insert/import questions programmatically

Generally AnsPress question can be inserted from from wp-admin and ask form. But sometimes we wants to insert question without using a form.

For using this tutorial you must have basic knowledge of WordPress and PHP. This tutorial require AnsPress 4.1.5 or above. At the time of writing this tutorial 4.1.5 was not released and can be downloaded only from AnsPress master branch.

By default AnsPress form have this fields:

  1. Post title (field name: post_title).
  2. Post content (field name: post_content).
  3. Is private (field name: is_private).
  4. Anonymous name (field name: anonymous_name).
  5. Post ID (field name: post_id).

Also few other fields are made available when ad-dons are enabled.

  1. Category (field name: category).
  2. Tags (field name: tags)

Source can be found here: AP_Form_Hooks::question_form().

We also have to make sure that the other addons continue to work properly. So to retain expected behavior we will add all of sanitized values to AnsPress form instead of directly using values.

Loading Gist...

We’are all done Its time to save question. Call below method:

Loading Gist...

Above method will return WP_Error object on error and post id on success.

Default qameta and activities will be added automatically once post is created. For inserting/updating custom meta and activities you can do this:

Loading Gist...

Complete code:

Loading Gist...

If you have any confusion then feel free to ask it on our support form.




  1. Can you add an import/ export function that the user just paste the question information on excel then upload to the website, which will save so much time.

  2. posting multiple questions together not working.


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment