douqiang5809
2015-09-27 19:19
浏览 44
已采纳

如何将逗号分隔列表(从选项页面)作为WordPress中的数组传递

I created a custom option menu in the Admin (Dashboard) page in WordPress.

The idea is to allow administrators to enter Post IDs to restrict as a comma separated value (e.g. "100, 102, 104") in Dashboard. I'd like to pass the comma separated value as an array to restrict access to the posts with the Post IDs.

To restrict the access, I tried to get the value in a theme file:

$restricted_ids = array();
$restricted_ids = get_option('_s_theme_options')['restricted_post_ids'];
if(is_single ($restricted_ids)) && !is_user_logged_in()) {
// My code here
}

I tested it and found that the variable "$restricted_ids" does not get the Post Ids as expected. For example, if I enter '123, 456', $restricted_ids receives it as an array with the values '1, 2, 3...' not '123, 456'. How can I correct the code for "$restricted_ids" to receive the entered Post Ids as an array correctly?

Thanks for your help.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsv73806 2015-09-27 20:08
    已采纳

    Try removing spaces from your string, and then splitting it into an array with explode():

    $restricted_ids = array();
    
    $post_ids = str_replace(' ', '', get_option('_s_theme_options')['restricted_post_ids']);
    $restricted_ids = explode(',', $post_ids);
    
    if(is_single ($restricted_ids) && !is_user_logged_in()) {
      // Do the things
    }
    
    点赞 评论

相关推荐 更多相似问题