Wordpress - 在发布时保存帖子中随机数字顺序的功能

时间:2014-12-11 15:36:45

标签: php wordpress

当在Wordpress中发布帖子时,我需要一种方法在两个列表中以随机顺序保存数字0-9,这样在编辑器中没有输入任何内容时,帖子将在帖子发布时显示类似的内容和这些数字将保存该帖子,但每个帖子的数字显示不同:

<ul class="list-one">
    <li class="box-1"> 7 </li>
    <li class="box-2"> 5 </li> 
    <li class="box-3"> 2 </li> 
    <li class="box-4"> 4 </li> 
    <li class="box-5"> 1 </li> 
    <li class="box-6"> 8 </li> 
    <li class="box-7"> 9 </li> 
    <li class="box-8"> 3 </li> 
    <li class="box-9"> 0 </li> 
    <li class="box-10"> 6 </li> 
</ul>
<ul class="list-two">
    <li class="box-1"> 8 </li>
    <li class="box-2"> 4 </li> 
    <li class="box-3"> 6 </li> 
    <li class="box-4"> 0 </li> 
    <li class="box-5"> 2 </li> 
    <li class="box-6"> 7 </li> 
    <li class="box-7"> 5 </li> 
    <li class="box-8"> 3 </li> 
    <li class="box-9"> 1 </li> 
    <li class="box-10"> 9 </li> 
</ul>

1 个答案:

答案 0 :(得分:0)

Loop中,您可以使用get_the_content功能获取帖子的内容,之后您可以将HTML添加到帖子中,然后echo

<强>更新

<?php
    ...

    // Get the post content
    $post_content = get_the_content;

    // Generate first list with random numbers
    $list_one = '<ul class="list-one">';

    for ($i = 0; $i < 10; $i++) {
        $list_one .= '<li class="box-'.($i + 1).'"> '.rand(0, 9).' </li>';
    }

    $list_one .= '</ul>';

    // Generate second list with random numbers
    $list_two = '<ul class="list-two">';

    for ($i = 0; $i < 10; $i++) {
        $list_two .= '<li class="box-'.($i + 1).'"> '.rand(0, 9).' </li>';
    }

    $list_two .= '</ul>';

    // Add the generated lists to the content

    $post_content .= $list_one.$list_two;

    // And then display it

    echo $post_content;

    ...
?>

更新2

您必须使用save_post操作。来自官方文件:

  

save_post 是在创建或更新帖子或页面时触发的操作,可以是导入,帖子/页面编辑表单,xmlrpc或邮件发送。

像这样使用:

function doSomething($post_id) {
    // fetch the post by ID, check if it is newly created,
    // generate your lists, append to it and update it
}

add_action( 'save_post', 'doSomething' );

这是一个细微差别,在文档中也会突出显示。要更新帖子,您需要调用wp_update_post函数,该函数将调用save_post。这将导致无限循环。为避免这种情况,您必须在函数内部remove_action,如下所示:

function doSomething($post_id) {
    // Remove your action
    remove_action( 'save_post', 'doSomething' );

    // fetch the post by ID, check if it is newly created,
    // generate your lists and append to it

    // Update the post
    wp_update_post(/* ... */);

    // Add your action again
    add_action( 'save_post', 'doSomething' );
}

add_action( 'save_post', 'doSomething' );

有关save_post的详细信息,请查看the official documentation