将帖子ID修改为增量,忽略具有自定义字段的帖子

时间:2016-01-11 15:14:15

标签: wordpress custom-fields

我正在尝试将post id修改为增量,同时忽略具有标题为“foldout”的自定义字段的帖子。我似乎无法让它工作,我没有得到任何PHP错误。我在functions.php文件的末尾有这个

function updateNumbers() {
/* numbering the published posts: preparation: create an array with the ID in sequence of publication date, /
/ save the number in custom field 'incr_number' of post with ID /
/ to show in post (within the loop) use <?php echo get_post_meta($post->ID,'incr_number',true); ?>
/ alchymyth 2010 */
global $wpdb;
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.post_status = 'publish' AND wposts.post_type = 'post' AND wpostmeta.meta_key != 'foldout'  ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
$counts = 5 ;
if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
$counts++;
add_post_meta($post->ID, 'incr_number', $counts, true);
update_post_meta($post->ID, 'incr_number', $counts);
endforeach;
endif;
}
add_action ( 'publish_post', 'updateNumbers' );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

我已将问题缩小到此处提到的查询字符串: https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query#Query_based_on_Custom_Field_and_Category

我可以让这个工作:

$querystr =    "SELECT $wpdb->posts.* 
                FROM $wpdb->posts 
                WHERE $wpdb->posts.post_status = 'publish' 
                AND $wpdb->posts.post_type = 'post' ";

但不是这样:

$querystr =   "SELECT wposts.* 
                FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
                WHERE wposts.ID = wpostmeta.post_id 
                AND wpostmeta.meta_key != 'foldout' 
                AND wposts.post_type = 'post' ";

我在“基于自定义字段的查询和按值排序”示例中进行了修改。

1 个答案:

答案 0 :(得分:1)

这似乎可以解决问题,通过Google搜索找到类似的答案。

$querystr = "
    SELECT ID, post_title, post_content FROM $wpdb->posts
    WHERE not exists ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = 'foldout')
    AND (post_status = 'publish')
    AND (post_type = 'post')
";