从Gutenberg SelectControl到PHP的前端获取价值

时间:2018-10-02 13:04:52

标签: javascript php wordpress wordpress-gutenberg

我有带有谷歌字体选择的简单古腾堡块。

el (SelectControl,
{   
    value: fontFamily,
    label: __('Шрифт'),
    options: [                                  
        {
            value: 'Georgia',
            label: 'Georgia'
        },
        { 
            value: 'PT Sans', 
            label: 'PT Sans' 
        },
        { 
            value: 'Amatic SC', 
            label: 'Amatic SC' 
        },
    ],
    onChange: onChangefontFamily,
},),

php:

function google_fonts_url() {   
  $fonts_url = '';  
  $font_families = array();
  $font_families[] = 'Amatic SC|PT Sans:400,400i';
  $query_args = array(
      'family' => urlencode( implode( '|', $font_families ) ),
      'subset' => urlencode( 'latin,cyrillic' ),
  );
  $fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );    
  return $fonts_url; }                                           

我只需要从Google加载选定的字体。

如何从选择中获取val?

1 个答案:

答案 0 :(得分:0)

Gutenberg将块的属性保存在post_content内的HTML注释中。因此,您需要使用PHP解析HTML注释。一种方法是使用DOMDocument

假设您的内容保存在post_content中,如下所示:

<!-- wp:yourprefix/yourblock {"fontFamily":"Amatic SC"} -->
 <div class="wp-block-yourprefix-yourblock"></div>
<!-- /wp:yourprefix/yourblock -->

然后,您可以使用以下方法获取帖子/页面的内容:

$content_post = get_post($my_postid);
$content = $content_post->post_content;

然后可以由DOMDocument库解析此内容,以提取以JSON编码的select的值

$dom = new DOMDocument();

//Pass the content to the loadHTML function
$dom->loadHTML($content);
$xpath = new DOMXPath($dom);

//Extract Comment Nodes
$comments = $xpath->query('//comment()');

//Extract text from the 1st node
$text = $comments->item(0)->data;

//Match the JSON string and decode to get the selected font value
preg_match('~\{(?:[^{}]|(?R))*\}~', $text,$res);
$fontFamily = json_decode($res[0])->fontFamily;