最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Plugin development - How to use a specific wp_options into the real rendered code in the front end?

programmeradmin5浏览0评论

I am learning php and Wordpress development. I created a plugin that shows a cookie bar. It works fine. I created also a options page, which successfully saves the selected values to the database.

However I am struggling in using those saved options into the real code.

For example here are the options I have:

function wprcb_api_text_field_cookieMessage_render()
{
    $options = get_option('wprcb_api_settings');
?>
    <input type='text' name='wprcb_api_settings[wprcb_api_text_field_cookieMessage]' value='<?php echo $options['wprcb_api_text_field_cookieMessage']; ?>'>
<?php
}

function wprcb_api_select_field_backgroundColor_render(  ) {
    $options = get_option( 'wprcb_api_settings' );
    ?>
    <select name='wprcb_api_settings[wprcb_api_select_field_backgroundColor]'>
        <option value='#000' <?php selected( $options['wprcb_api_select_field_backgroundColor'], 1 ); ?>>Black</option>
        <option value='#fff' <?php selected( $options['wprcb_api_select_field_backgroundColor'], 2 ); ?>>White</option>
    </select>

<?php
}

Those two options allow me to choose a text (the first function) and a select menu to choose black or white background color (second function).

And here is the front end:

function wprcb_inject_html_into_footer()
{
    echo <<<COOKIEBARHTML
  <div id="wprcb-cookie-bar" class="wprcb-cookie-bar" style="display: flex;">
  <div>
    <div class="wprcb-content">
      <p class="wprcb-text">This site uses internal and external cookies provide and improve our services. By using our site, you grant consent to cookies.</p>
      <a class="accept-button" id="accept-button" href="#">Accept</a>
      <a class="learn-more" href="{$GLOBALS['wprcb_policy']}" target="_blank" rel="nofollow">Learn more</a>
      </div>
  </div>
</div>   
COOKIEBARHTML;
}
add_action('wp_footer', 'wprcb_inject_html_into_footer');

I tried to change the line

  <div id="wprcb-cookie-bar" class="wprcb-cookie-bar" style="display: flex;">

to

  <div id="wprcb-cookie-bar" class="wprcb-cookie-bar" style="display: flex; background:{$options['wprcb_api_select_field_backgroundColor']}">

But it seems to to use the value. Also I tried to change

<p class="wprcb-text">This site uses internal and external cookies provide and improve our services. By using our site, you grant consent to cookies.</p>

to

<p class="wprcb-text">$wprcb_api_settings[wprcb_api_text_field_cookieMessage]</p>

But also that's not the right way to do. And this second specific case should have a default value, which should be used by default, for example when the plugin is newly installed and the setting was not changed by the user.

I'd like to ask you for help how to use those saved value in these 2 specific examples and how to use a default text for the text field.

Thanks

发布评论

评论列表(0)

  1. 暂无评论