我有一个函数,它对给定作者的所有帖子都有一个循环。我使用get_current_user_id()
但这在循环中似乎不起作用,或者可能是它的短代码问题。我的函数在shortcode的帮助下运行。
当前用户总是返回0,因此它会显示我网站上所有帖子的元数据。
function get_meta_value_by_meta_key(){
$author_id = \'get_current_user_id()\';
// do stuff to get user I
$author_posts = get_posts( array(\'author\' => $author_id, \'numberposts\' => -1 ));
// needed to collect the total sum of views
$counter = 0;
// needed to collect the total sum of views echo
\'<h3>Post views by Author:</h3><ul>\';
// do stuff to get author name
foreach ( $author_posts as $post ) {
$views = absint( get_post_meta( $post->ID, \'Creation_Views\', true ) );
$counter += $views;
echo "<li>{$post->post_title} ({$views})</li>";
}
echo "</ul><hr /><p>Total Number of views: <strong>{$counter}</strong></p>";
}
add_shortcode(\'Stats\', get_meta_value_by_meta_key);
如何修改它以将当前用户id作为
$author_id
我还试图手动验证其他一切是否正常,所以我只需将我的用户id放入$author_id
而且效果很好。
仅供参考:我从WPSE上的另一个答案中提取了这段代码片段,唯一的问题是,答案没有说明如何获取当前的作者id,这就是问题所在。我希望这些信息能有所帮助。
最合适的回答,由SO网友:Chetan Vaghela 整理而成
您已添加get_current_user_id();
在单引号中。请从中删除报价\'get_current_user_id()\';
.
function get_meta_value_by_meta_key(){
$author_id = get_current_user_id();
// do stuff to get user I
$author_posts = get_posts( array(\'author\' => $author_id, \'numberposts\' => -1 ));
// needed to collect the total sum of views
$counter = 0;
// needed to collect the total sum of views
echo \'<h3>Post views by Author:</h3><ul>\';
// do stuff to get author name
foreach ( $author_posts as $post ) {
$views = absint( get_post_meta( $post->ID, \'Creation_Views\', true ) );
$counter += $views;
echo "<li>{$post->post_title} ({$views})</li>";
}
echo "</ul><hr /><p>Total Number of views: <strong>{$counter}</strong></p>";
}
add_shortcode(\'Stats\', \'get_meta_value_by_meta_key\');