0

I am creating a custom admin panel where the admin can choose between 3 layout using radio buttons. Everything works perfectly except when admin creates a new page there isn't default option.

I solved this by using:

if ($layout == "") {
  $layout = "layout_1";
}

I hope someone can help me with a better solution to set up default value for the newly created pages meta

Here is the full code:

function page_layout_metabox(){
    add_meta_box( 'page_layout_selector', 'Page Settings', 'page_layout_selector', 'page', 'normal', 'high' );
}
function page_layout_selector(){
$layout = get_post_meta(get_the_ID(), 'layout', true);
//set default
if ($layout == "") {
  $layout = "layout_1";
}
?>
<div id="page_layout_container">
  <p id="page_layout_title">Page layout</p>
  <div class="radio_container">
    <div class="form">
      <label>
        <input type="radio" name="layout" id="layout_1" value="layout_1" <?php if ($layout == "layout_1" ) echo "checked";?>>
        <div class="radio" id="layout_1">
          <span class="icon-on"></span>
        </div>
      </label>
    </div>
    <div class="form">
      <label>
        <input type="radio" name="layout" id="layout_2" value="layout_2" <?php if ($layout == "layout_2" ) echo "checked";?>>
        <div class="radio" id="layout_2">
          <span class="icon-on"></span>
        </div>
      </label>
    </div>
    <div class="form">
      <label>
        <input type="radio" name="layout" id="layout_3" value="layout_3" <?php if ($layout == "layout_3" ) echo "checked";?>>
        <div class="radio" id="layout_3">
          <span class="icon-on"></span>
        </div>
      </label>
    </div>
  </div>
</div>

1 Answer 1

2

Yea. It seems everything is right. But I would prefer-

if (empty($layout)) {
  $layout = "layout_1";
}

instead of this-

if ($layout == "") {
  $layout = "layout_1";
}

It's the preferred method to test if the variable is empty or not. And I would also prefer-

if ($layout === "layout_1" ) echo "checked"
if ($layout === "layout_2" ) echo "checked"
if ($layout === "layout_3" ) echo "checked" 

Instead of this-

if ($layout == "layout_1" ) echo "checked"
if ($layout == "layout_2" ) echo "checked"
if ($layout == "layout_3" ) echo "checked" 

Otherwise it seems quite normal. Hope that helps you.

2
  • Thanks for the improvement in the code I will update it as you described!
    – István
    Aug 22, 2016 at 16:32
  • Well if this answer helped you, would you please accept the answer ? It would be great. @iwan
    – CodeMascot
    Aug 22, 2016 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.