【问题标题】:Get value from Gutenberg SelectControl to php for frontend从 Gutenberg SelectControl 获取价值到前端的 php
【发布时间】:2019-03-07 14:46:52
【问题描述】:

我有简单的 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; }                                           

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

如何从 select 中获取 val?

【问题讨论】:

    标签: javascript php wordpress wordpress-gutenberg


    【解决方案1】:

    Gutenberg 将块的属性保存在 post_content 内的 HTML cmets 中。因此,您需要使用 PHP 解析 HTML cmets。一种方法是使用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;
    

    【讨论】:

    • 更好的方法 - wordpress.org/gutenberg/handbook/designers-developers/… 和 webfont: jQuery(document).ready(function($) { fonts = []; $('.wp-block-writer').each(function( ) { font = this.style.fontFamily; font = font.replace(/\"/g, ""); if (font != 'Georgia') fonts.push(font); }); if (fonts != '') { WebFont.load({ google: { family: fonts } }); } });
    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2014-04-16
    • 2019-07-20
    相关资源
    最近更新 更多