Skip to content

Commit 59d21f1

Browse files
author
Antti Kuosmanen
committed
Support custom attributes in form tag via shortcode
Fixes #9
1 parent 8f056d9 commit 59d21f1

1 file changed

Lines changed: 25 additions & 7 deletions

File tree

classes/class-cpt-wplf-form.php

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -495,25 +495,35 @@ function strip_form_tags( $content ) {
495495
/**
496496
* The function we display the form with
497497
*/
498-
function wplf_form( $id, $content = '', $xclass = '' ) {
498+
function wplf_form( $id, $content = '', $xclass = '', $attributes = [] ) {
499499
global $post;
500500

501501
if ( 'publish' === get_post_status( $id ) || 'true' === $_GET['preview'] ) {
502502
if ( empty( $content ) ) {
503-
// you can override the content via a parameter
503+
// you can override the content via parameter
504504
$content = get_post( $id )->post_content;
505505
}
506506

507507
ob_start();
508508
?>
509509
<form
510+
data-form-id="<?php echo intval( $id ); ?>"
510511
class="libre-form libre-form-<?php echo esc_attr( $id . ' ' . $xclass ); ?>"
511512
<?php
512513
// check if form contains file inputs
513-
if ( strpos( $content, "type='file'" ) >= 0 || strpos( $content, 'type="file"' ) >= 0 ) {
514-
echo "enctype='multipart/form-data'";
514+
if ( strpos( $content, "type='file'" ) >= 0
515+
|| strpos( $content, 'type="file"' ) >= 0
516+
|| strpos( $content, 'type=file' ) >= 0
517+
) : ?>
518+
enctype="multipart/form-data"
519+
<?php endif; ?>
520+
<?php
521+
// add custom attributes from shortcode to <form> element
522+
foreach ( $attributes as $attr_name => $attr_value ) {
523+
echo esc_attr( $attr_name ) . '="' . esc_attr( $attr_value ) . "\"\n";
515524
}
516525
?>
526+
517527
>
518528
<?php if ( is_singular( 'wplf-form' ) && current_user_can( 'edit_post', $id ) ) {
519529
$publicly_visible = $this->get_publicly_visible_state( $id );
@@ -579,14 +589,22 @@ function maybe_enqueue_frontend_script() {
579589
/**
580590
* Shortcode for displaying a Form
581591
*/
582-
function shortcode( $attributes ) {
592+
function shortcode( $shortcode_atts ) {
583593
$attributes = shortcode_atts( array(
584594
'id' => null,
585595
'xclass' => '',
586-
), $attributes );
596+
), $shortcode_atts, 'libre-form' );
597+
598+
// we don't render id and class as <form> attributes
599+
$id = $attributes['id'];
600+
$xclass = $attributes['xclass'];
601+
$attributes = array_diff_key( $shortcode_atts, array(
602+
'id' => null,
603+
'xclass' => null,
604+
) );
587605

588606
// display form
589-
return $this->wplf_form( $attributes['id'], null, $attributes['xclass'] );
607+
return $this->wplf_form( $id, null, $xclass, $attributes );
590608
}
591609

592610

0 commit comments

Comments
 (0)