Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.