Skip to content

Instantly share code, notes, and snippets.

@alex-georgiou
Last active February 7, 2020 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-georgiou/2299b24680e4fe5258ac0285044b8e56 to your computer and use it in GitHub Desktop.
Save alex-georgiou/2299b24680e4fe5258ac0285044b8e56 to your computer and use it in GitHub Desktop.
How to write better HTML markup in WordPress
<?php
/**
* Renders a form whenever the <code>[my_form name="string" age="integer"]</code> shortcode is triggered.
*/
function my_form( $atts, $content, $tag ) {
$defaults = array(
'name' => 'Anonymous',
'age' => 18,
);
$atts = shortcode_atts(
$defaults,
$atts,
$tag
);
$id = uniqid( 'form' );
$html = '<form id="' . esc_attr( $id ) . '">';
$html .= '<input type="text" name="name" placeholder="' . esc_attr( 'Enter your name', 'langdomain' ) . '" value="' . esc_attr( $atts['name'] ) . '" />';
$html .= '<input type="number" name="age" placeholder="' . esc_attr( 'Enter your age', 'langdomain' ) . '" value="' . absint( $atts['age'] ) . '" />';
$html .= '<button type="submit">' . esc_html( 'Submit', 'langdomain' ) . '</button>';
$html .= '</form>';
return $html;
}
add_shortcode( 'my_form', 'my_form' );
<?php
/**
* Renders a form whenever the <code>[my_form name="string" age="integer"]</code> shortcode is triggered.
*/
function my_form( $atts, $content, $tag ) {
$defaults = array(
'name' => 'Anonymous',
'age' => 18,
);
$atts = shortcode_atts(
$defaults,
$atts,
$tag
);
$id = uniqid( 'form' );
ob_start();
?>
<form id="<?php esc_attr_e( $id ); ?>">
<input type="text" name="name" placeholder="<?php esc_attr_e( 'Enter your name', 'langdomain' ); ?>" value="<?php esc_attr_e( $atts['name'] ); ?>" />
<input type="number" name="age" placeholder="<?php esc_attr_e( 'Enter your age', 'langdomain' ); ?>" value="<?php esc_attr_e( $atts['age'] ); ?>" />
<button type="submit"><?php esc_html_e( 'Submit', 'langdomain' ); ?></button>
</form>
<?php
return ob_get_clean();
}
add_shortcode( 'my_form', 'my_form' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment