Creazione di un post

  programmazione wordpress, wordpress

  function create_wordpress_post_with_code() {
    
    // Set the post ID to -1. This sets to no action at moment
    $post_id = -1;

    // Set the Author, Slug, title and content of the new post
    $author_id = 1;
    $slug = 'wordpress-post-created-with-code';
    $title = 'WordPress post created whith code';
    $content = 'Contenuto del post';
    // Cheks if doen't exists a post with slug "wordpress-post-created-with-code".
    if( !post_exists_by_slug( $slug ) ) {
        // Set the post ID
        $post_id = wp_insert_post(
            array(
                'comment_status'	=>	'closed',
                'ping_status'		=>	'closed',
                'post_author'		=>	$author_id,
                'post_name'		    =>	$slug,
                'post_title'		=>	$title,
                'post_content'      =>  $content,
                'post_status'		=>	'publish',
                'post_type'		    =>	'post'
            )
        );
    } else {

            // Set pos_id to -2 becouse there is a post with this slug.
            $post_id = -2;
    
    } // end if

} // end oaf_create_post_with_code
add_filter( 'after_setup_theme', 'create_wordpress_post_with_code' );
/**
* post_exists_by_slug.
*
* @return mixed boolean false if no post exists; post ID otherwise.
*/
function post_exists_by_slug( $post_slug ) {
$args_posts = array(
    'post_type'      => 'post',
    'post_status'    => 'any',
    'name'           => $post_slug,
    'posts_per_page' => 1,
);
$loop_posts = new WP_Query( $args_posts );
if ( ! $loop_posts->have_posts() ) {
    return false;
} else {
    $loop_posts->the_post();
    return $loop_posts->post->ID;
}
}

SCRIVI UN COMMENTO