0

I am trying to create a simple plugin that creates only one new post. The code I have written creates a the same new post every second. Below is the code I have. What would need to be added so it creates only one post?

<?php
/**
*@package blog-poster
*/
/*
Plugin Name: Blog Poster
Plugin URI: http://www.litliving.com
Description: This is a plugin for Litliving customers that allows for blog posts to be automatically posted.
Version: 1.0.0
Author: Ben Smith
Author URI: http://www.bengsmith.com
*/

if ( ! defined( 'ABSPATH') ){
  die;
}


function AddThisPage() {
    global $wpdb; // Not sure if you need this, maybe

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

    wp_insert_post($page);

}

add_action( 'wp_insert_post', 'AddThisPage' );

register_activation_hook( __FILE__, 'AddThisPage' );
?>

2 Answers 2

0

Your plugin does no checking at all, such as “does the post already exists?” Accordingly, it creates a post each time WordPress is called.

There is a system called WordPress heartbeat, which contacts the server every few seconds. Your plugin is called each time, and a post is created.

For reference, the Heartbeat doc.

0
0

Thanks for the reply. Ironically, after I had posted this I found the answer. I needed to create an if else statement at the bottom. I write

$page_exists = get_page_by_title( $page['post_title'] );

    if( $page_exists == null ) {

        $insert = wp_insert_post( $page );
        if( $insert ) {

        }
    } else {

    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.