我正在使用wordpress网站和内部自定义PHP srcipt,它将与CRON一起运行以更新帖子。
我的看法:
我如何做:
$pages = $wpdb->get_results(
"
SELECT post_title, id
FROM $wpdb->posts
WHERE post_status = 'publish'
AND post_type = 'post'
"
);
if( $pages ) {
foreach ( $pages as $page ) {
echo $page->post_title . " - ";
echo $page->id . "<br>";
}
}
所以问题是:问题出在MySQL查询上。我需要以下响应:array [0]-> ID(来自帖子),post_title(来自帖子),meta_value(来自postmeta,其中meta_key ='src_link')。我如何获得此回复?
我尝试了此操作-但ID无效:
SELECT post_title, id, meta_value
FROM $wpdb->posts as post
INNER JOIN $wpdb->postmeta as meta ON post.id=meta.post_id
WHERE post.post_status = 'publish'
AND post.post_type = 'post'
AND meta.meta_key='src_link'
问题是当我添加此行时-
AND meta.meta_key='src_link'
找不到任何东西。如果我删除此行。它会找到我需要的,但带有dupclicates(我只需要其中Meta_key ='src_link'的行。
表格:
帖子:
-------------------
id | post_title
------------------
1 | new title here
------------------
2 | again a title here
后期元:
meta_id | post_id | meta_key | meta_value
---------------------------------------------
1 | 2 | src_link | here_is_my_link
---------------------------------------------
2 | 1 | empty | not_my_link
答案 0 :(得分:1)
您可以像
那样使用 INNER JOIN
SELECT post_title, id, meta_key
FROM $wpdb->posts as post
INNER JOIN $wpdb->postmeta as meta ON post.id=meta.post_id
WHERE post_status = 'publish' and meta.meta_key='src_link'
AND post_type = 'post'
答案 1 :(得分:0)
当您使用全局$wpdb
时,我们可以假定您的PHP在WP框架内 。因此,您不需要自定义SQL查询-您可以使用标准的WP_Query:
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'src_link',
'compare' => 'EXISTS',
),
),
);
$postsQuery = get_posts($args);
foreach ($postsQuery as $myPost) {
// We're using $myPost rather than $post as the latter is a global var used in The Loop
echo '<pre>' . print_r($myPost, true) . '</pre>';
update_post_meta($myPost->ID, 'updated_link', $myCustomValue);
}
在这里,我们获取状态为post
的所有 类publish
型帖子,并使用meta_query
查找其中src_link
的帖子存在。
答案 2 :(得分:0)
尝试一下:
SELECT post_title, id, meta_key
FROM $wpdb->posts as post
INNER JOIN $wpdb->postmeta as meta ON post.id=meta.post_id and meta.meta_key='src_link'
WHERE post_status = 'publish'
AND post_type = 'post'