Wordpress以编程方式创建帖子,然后在index.php上显示帖子

时间:2013-02-02 11:14:12

标签: php wordpress

我一直在尝试这个项目一段时间,我没有运气。我正在尝试在functions.php中以编程方式创建8个帖子。我需要这些只发布1次。我一直遇到的问题是每次刷新页面时帖子都会自动创建更多。这是我在functions.php中以编程方式创建帖子的代码。

<?php // Create post object
$my_post = array(
     'post_title' => 'How to make your diet success',
     'post_name' => '7-ways-to-make-succes-Diet',
     'post_content' => 'my content',
     'post_status' => 'publish',
     'post_author' => 1,
     'post_category' => array(8,39)
  );

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

此代码的唯一问题是每次页面刷新时自动创建更多帖子。我将创建其中的8个函数,我只希望它们创建一次。代码示例会很棒。


接下来,我想在index.php上显示帖子。我想单独发布这些帖子。这是我到目前为止的代码。

<div class="post1"><?php $post_id = wp_insert_post( $post, $wp_error );
//now you can use $post_id withing add_post_meta or update_post_meta ?> </div>

<div class="post2"><?php $post_id = wp_insert_post( $post, $wp_error );
//now you can use $post_id withing add_post_meta or update_post_meta ?> </div>

我很确定我需要调用slug或post name来单独获取它们。是的,我尝试过这种方法以及其他10种方法,但没有任何效果。我得到的最接近的是显示帖子名称。代码示例会很棒。我会非常感激,如果有人可以为我工作,我可能会通过PayPal捐出一些钱。感谢。

1 个答案:

答案 0 :(得分:2)

functions.php不是以编程方式创建页面或帖子的好地方。您应该create a plugin(创建自定义主题很简单)并在其activation function中创建帖子。仅在您的插件激活时调用此函数。另请阅读插件deactivationuninstall挂钩

您的帖子一次又一次被创建的原因是每次请求页面时都会调用files.php文件。如果你坚持在functions.php中创建帖子,你应该用一个条件来包装你的wp_insert_post,看看你的帖子是否已经创建 - 而get_posts函数是否符合你的需要。

<?php 
//Use either post slug (post_name)
$post = get_posts( array( 'name' => '7-ways-to-make-success-diet' ) );
/*or $post = get_posts( array( 'name' => sanitize_title('My Single.php Test') ) );
if you do not set the post_name attribute and let WordPress to set it up for you */
if ( empty($post) ) {
    // Create post object 
    $my_post = array( 'post_title' => 'My Single.php Test', 'post_name' => '7-ways-to-make-success-diet', 'post_content' => 'my content4654654', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(8,39) ); 
    // Insert the post into the database 
    wp_insert_post( $my_post ); 
}
?>

此外,get_posts将帮助您将您的帖子带到首页。例如

<?php 
$post = get_posts( array( 'name' => 'How to make your diet success' ) );
echo $post->post_title;
...
?>