Skip Navigation

[Resolved] Automatically inserting post when none is found in archive

This support ticket is created 4 years, 1 month ago. There's a good chance that you are reading advice that it now obsolete.

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.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

This topic contains 1 reply, has 2 voices.

Last updated by Waqar 4 years, 1 month ago.

Assisted by: Waqar.

Author
Posts
#1796717

Hi,

I have an archive page. Can I achieve this feature? If a user searches through an archive page and no result returned, then it can automatically insert an entry of that custom type with a default value.

#1799917

Hi,

Thank you for waiting, while I performed some tests.

To automatically insert a post, you can use WordPress's "wp_insert_post" function, in a custom shortcode, for example:
( ref: https://developer.wordpress.org/reference/functions/wp_insert_post/ )


add_shortcode('no_results_auto_post', 'no_results_auto_post_func');
function no_results_auto_post_func() {

	$my_post = array(
		'post_title'    => 'My post',
		'post_content'  => 'This is my post.',
		'post_status'   => 'publish',
		'post_author'   => 1,
	);

	// Insert the post into the database.
	wp_insert_post( $my_post );

}

To execute this custom shortcode, when no results are found in view or WordPress Archive, you can place this custom shortcode inside the [wpv-no-items-found] ... [/wpv-no-items-found] tags, in the "Loop Editor" section.

Example:


[wpv-no-items-found]
	<strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
	[no_results_auto_post]
[/wpv-no-items-found]

Note: The custom code examples from our forum are shared to get you started in the right direction. You're welcome to adjust them as needed and for more personalized customization assistance, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/

regards,
Waqar