Создание контактной формы без плагина [закрыто]
Я новичок в разработке Wordpress и я устал бороться с контактной формой 7, чтобы оформить ее так, как мне хотелось бы. Возможно ли и не считается "плохой практикой" размещать html-форму на моей странице контактов и размещать ее на странице php, которая обрабатывает отправку формы? Или это просто не делается?
3 answers
Это моя очень простая реализация контактной формы:
class WPSE_299521_Form {
/**
* Class constructor
*/
public function __construct() {
$this->define_hooks();
}
public function controller() {
if( isset( $_POST['submit'] ) ) { // Submit button
$full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );
$email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );
$color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );
$accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
$comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );
// Send an email and redirect user to "Thank you" page.
}
}
/**
* Display form
*/
public function display_form() {
$full_name = filter_input( INPUT_POST, 'full_name', FILTER_SANITIZE_STRING );
$email = filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING | FILTER_SANITIZE_EMAIL );
$color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );
$accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
$comments = filter_input( INPUT_POST, 'comments', FILTER_SANITIZE_STRING );
// Default empty array
$accessories = ( $accessories === null ) ? array() : $accessories;
$output = '';
$output .= '<form method="post">';
$output .= ' <p>';
$output .= ' ' . $this->display_text( 'full_name', 'Name', $full_name );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_text( 'email', 'Email', $email );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_radios( 'color', 'Color', $this->get_available_colors(), $color );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_checkboxes( 'accessories', 'Accessories', $this->get_available_accessories(), $accessories );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' ' . $this->display_textarea( 'comments', 'comments', $comments );
$output .= ' </p>';
$output .= ' <p>';
$output .= ' <input type="submit" name="submit" value="Submit" />';
$output .= ' </p>';
$output .= '</form>';
return $output;
}
/**
* Display text field
*/
private function display_text( $name, $label, $value = '' ) {
$output = '';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
$output .= '<input type="text" name="' . esc_attr( $name ) . '" value="' . esc_attr( $value ) . '">';
return $output;
}
/**
* Display textarea field
*/
private function display_textarea( $name, $label, $value = '' ) {
$output = '';
$output .= '<label> ' . esc_html__( $label, 'wpse_299521' ) . '</label>';
$output .= '<textarea name="' . esc_attr( $name ) . '" >' . esc_html( $value ) . '</textarea>';
return $output;
}
/**
* Display radios field
*/
private function display_radios( $name, $label, $options, $value = null ) {
$output = '';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
foreach ( $options as $option_value => $option_label ):
$output .= $this->display_radio( $name, $option_label, $option_value, $value );
endforeach;
return $output;
}
/**
* Display single checkbox field
*/
private function display_radio( $name, $label, $option_value, $value = null ) {
$output = '';
$checked = ( $option_value === $value ) ? ' checked' : '';
$output .= '<label>';
$output .= ' <input type="radio" name="' . esc_attr( $name ) . '" value="' . esc_attr( $option_value ) . '"' . esc_attr( $checked ) . '>';
$output .= ' ' . esc_html__( $label, 'wpse_299521' );
$output .= '</label>';
return $output;
}
/**
* Display checkboxes field
*/
private function display_checkboxes( $name, $label, $options, $values = array() ) {
$output = '';
$name .= '[]';
$output .= '<label>' . esc_html__( $label, 'wpse_299521' ) . '</label>';
foreach ( $options as $option_value => $option_label ):
$output .= $this->display_checkbox( $name, $option_label, $option_value, $values );
endforeach;
return $output;
}
/**
* Display single checkbox field
*/
private function display_checkbox( $name, $label, $available_value, $values = array() ) {
$output = '';
$checked = ( in_array($available_value, $values) ) ? ' checked' : '';
$output .= '<label>';
$output .= ' <input type="checkbox" name="' . esc_attr( $name ) . '" value="' . esc_attr( $available_value ) . '"' . esc_attr( $checked ) . '>';
$output .= ' ' . esc_html__( $label, 'wpse_299521' );
$output .= '</label>';
return $output;
}
/**
* Get available colors
*/
private function get_available_colors() {
return array(
'red' => 'Red',
'blue' => 'Blue',
'green' => 'Green',
);
}
/**
* Get available accessories
*/
private function get_available_accessories() {
return array(
'case' => 'Case',
'tempered_glass' => 'Tempered glass',
'headphones' => 'Headphones',
);
}
/**
* Define hooks related to plugin
*/
private function define_hooks() {
/**
* Add action to send email
*/
add_action( 'wp', array( $this, 'controller' ) );
/**
* Add shortcode to display form
*/
add_shortcode( 'contact', array( $this, 'display_form' ) );
}
}
new WPSE_299521_Form();
После вставки кода вы можете использовать короткий код [contact]
для его отображения.
Все плагины форм ужасны, просто формы, как правило, очень сложны для правильного кодирования, особенно когда администратор сайта должен иметь возможность их разрабатывать.
Нет ничего плохого в том, чтобы самостоятельно кодировать форму, просто вам, вероятно, потребуется воссоздать материал, который другие люди уже усовершенствовали, или, по крайней мере, иметь хорошие основы для (форматирования электронных писем, хранения в БД и, возможно, больше).
Так что это действительно зависит от вашего конкретного требования, если гибкость не требуется, и отправка электронной почты достаточно хороша, должно быть проще написать свое собственное, чем "бороться" с плагинами.
Поскольку вы не выполняете CRUD в БД, я не понимаю, почему бы и нет. Я делал это раньше, когда использовал шаблон страницы для обработки формы и указывал свой контакт <form ...>
action
к нему action="<?php echo home_url( 'my-form-processing-page-template-slug' ); ?>"
.
В качестве альтернативы, используйте фактический тип одного сообщения для его обработки, т.Е. action="<?php echo get_the_permalink();?>"
(должен быть is_single() || is_singular()
для использования get_the_permalink()
).