当一篇文章在 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>
在 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
的更多详细信息,请查看官方文档。