<?php /* Template Name: CustomPageT1 */ ?>
<?php get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
// Start the loop.
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'template-parts/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) {
comments_template();
}
// End of the loop.
endwhile;
?>
</main><!-- .site-main -->
<?php get_sidebar( 'content-bottom' ); ?>
</div><!-- .content-area -->
<!-- custom code -->
<?php
$title_add="testing php post";
$content_add="<p align='justify'>just testing the add post using custom php</p>";
// Create post object
$my_post = array(
'post_id' => 22,
'post_title' => $title_add,
'post_content' => $content_add,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array( 8,39 )
);
// Insert the post into the database
wp_insert_post( $my_post );
add_post_meta(22,'_testing_post_meta_add','just text to let see if this is working');
function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
// Make sure meta is added to the post, not a revision.
if ( $the_post = wp_is_post_revision($post_id) )
$post_id = $the_post;
return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
}
?>
<!-- end custom code -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
but it didn’t work, any help or tip will be very useful.
thanks in advance!
]]>You need to rename add_post_meta() because there’s already a WP function by that name. It’s a good idea to add your plugin’s or theme’s (or your own) initials to all functions and classes to avoid conflicts with other code.
With those adjustments, everything seems to work fine. Here’s some other details that I may have glossed over that you need to address for this to all work.
Add this code page to your theme’s folder. It can be any name with a PHP extension, as long as it doesn’t already exist.
Create a new page. Assign a title, and content along the lines of “A new post was just created!” is not required, but a good idea IMO. Select “CustomPageT1” as the template for the page. Publish it.
Anytime someone views this page, your code will run and insert a new post. It’d probably be a good idea to add code that checks the logged in user is you. If someone requesting the page is not logged in or is not you (or someone authorized to add posts), either skip over the insertion code or die with a message like “This page is not for you.” As it is now, any search bot scraping your site could be adding new posts!
]]>