我希望在Wordpress上为每个页面创建一些post meta。这一点有点用于分类。每个顶级页面都有一个字母,如A B C D等。顶级页面的每个子页面都有一个数字,如01,02,03,04。我试图修改我的代码以进行发布/更新/删除,以便相应地添加/更新元,无论页面是否被删除或添加。我的问题是如何检查它是顶级页面还是正在保存的子页面?代码似乎只使用代码的顶级部分,无论是否为父级,都会保存不同的字母。
function updateNumbers($post) {
global $wpdb;
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'page' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
if($post->post_parent > 0) {
//Child Page
$counts = 01;
if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
$counts++;
$parent_letter = get_post_meta($post->post_parent, 'incr_letter', true);
add_post_meta($post->ID, 'incr_number', $counts, true);
update_post_meta($post->ID, 'incr_number', $counts);
add_post_meta($post->ID, 'incr_letter', $parent_letter, true);
update_post_meta($post->ID, 'incr_letter', $parent_letter);
endforeach;
endif;
}else {
//Top Level Page
$counts = A;
if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
$counts++;
add_post_meta($post->ID, 'incr_letter', $counts, true);
update_post_meta($post->ID, 'incr_letter', $counts);
endforeach;
endif;
}
}
add_action ( 'publish_post', 'updateNumbers' );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );
所需的层次结构与此类似:
- Page 1 - A.01
- Page 2 - B.01
-- Page 2 Child - B.02
-- Page 2 Child - B.03
-- Page 2 Child - B.04
- Page 3 - C.01
- Page 4 - D.01
答案 0 :(得分:0)
您的代码存在许多问题:
$post->post_parent == 0
而不是大于0,如果0作为字符串传递,则可以为真。反正:
function updateNumbers($post) {
global $wpdb;
// you had your query wrong..the loop was prob empty..
$querystr = "SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'page' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
if($post->post_parent == 0) {
//Top Level Page
$counts = "A"; //string
// Loop over all posts for every save, update, etc..... expensive
}else {
// Loop over all posts for every save, update, etc..... expensive
}
}
但是你要做的事情已经存在,wp有它的系统来识别等等的孩子。