根据登录的用户信息将Post Loop设置为短代码

时间:2021-09-22 作者:RobH

我在用户配置文件上有一个follower按钮,用户可以在其中跟踪其他用户。我有一个页面模板,显示当前登录用户遵循的所有帖子。我想为此创建一个快捷码[following\\u loop],并将查询添加到函数中。php。我无法使用快捷方式。

这是我使用的页面模板。我怎样才能把它输入到短代码中?

function register_shortcodes(){
   add_shortcode(\'following_users\', \'following_users_function\');
}
add_action( \'init\', \'register_shortcodes\');
function following_users_function () {

    $currentloggedinuser = get_current_user_id();

  // Get array containing only the user_id1 values.

  $followers = $wpdb->get_col(
    $wpdb->prepare(
      "SELECT user_id1 FROM {$wpdb->prefix}followers WHERE user_id2 = %d",
      $currentloggedinuser      
    )   
  );

  sort($followers); // or apply sorting in the query above

  // Directly echo the imploded array. 
  echo implode(\', \', $followers);

  $args = array(
    \'author__in\'=> $followers, //use the array we got from the query
    \'post_type\' => \'post\'
  );
    
    if (have_posts()) :
      while (have_posts()) : the_post();
         $return_string = \'<a href="\'.get_permalink().\'">\'.get_the_title().\'</a>\';
      endwhile;
   endif;
    
    wp_reset_query();
   return $return_string;
}
提前感谢:)

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

我无法使用快捷方式。

所以我明白了$args 因此,如果您确实希望帖子与这些参数匹配,那么您可以create a secondary query/loop like so:(替换if (have_posts()) :wp_reset_query();):

global $post;

// Create a secondary query
$query = new WP_Query( $args );

// Define the variable which stores the shortcode output
$return_string = \'\';

// Run the custom loop and append the output to $return_string. Remember, no echo!
if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();
        $return_string .= \'<a href="\'.get_permalink().\'">\'.get_the_title().\'</a>\';
    endwhile;

    wp_reset_postdata(); // restore the $post global - don\'t call wp_reset_query()
endif;
并确保添加global $wpdb; 在函数的顶部,因为当前该变量未在该函数中定义。

还有,请do not echo 因为它可以使REST API响应无效,并导致块编辑器无法保存帖子!所以一定要把它去掉echo implode(...);.

相关推荐

Ordering terms whilst in loop

我有一个页面模板,显示所有;“发布”;在两个自定义分类中,帖子显示在一个表中$type = $_GET[\'type\']; $category = $_GET[\'category\']; args = array( \'post-type\' => \'literature\', \'posts_per_page\' => -1, \'tax_query\' => array(