理论对你来说可能很难,但实际上很清楚你在努力实现什么。
短代码是将动态内容插入页面(或帖子)的好方法,您的想法失败的地方是“动态短代码”的概念。
使用快捷码将表单插入到内容中,并让回调处理提交后发生的事情。
熟悉how forms are handled in PHP 和difference between HTTP-POST and HTTP-GET (Resource 2, Resource 3).
练习将以下内容作为概念证明,而不是复制/粘贴就绪的解决方案:
短代码:[wpse_161632_sports_selection_form]
PHP:
<?php
/*
Plugin Name: WPSE_161632
Plugin URI: http://wordpress.stackexchange.com/questions/161632/
Description: Shortcode form handler example
Version: 1.0
Author: Johannes Pilkahn
License: GPL3
*/
/* Copyright 2014 Johannes Pilkahn
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 3, as
published by the Free Software Foundation.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
if ( ! class_exists( \'WPSE_161632\' ) ) :
class WPSE_161632 {
/**
* Form handler
*
* @since 1.0
* @access public
* @see constructor
*/
public function form_handler( $atts = \'\' )
{
// only relevant if the SC is supposed to have extra parameters
extract( shortcode_atts( array(
\'example_attribute\' => 1
), $atts ) );
if ( ( isset( $_POST[\'types\'] ) ) {
foreach( $_POST[\'types\'] as $type ) {
// do something
}
$this->output( true );
} else {
$this->output( false );
}
}
/**
* Outputs the form
*
* @since 1.0
* @access public
* @param bool $output
*/
public function output( $submitted )
{
$options = array(
array(
\'value\' => \'skateboarding\'
\'label\' => __( \'Skateboarding\', \'your-text-domain\' )
),
array(
\'value\' => \'basketball\'
\'label\' => __( \'Basketball\', \'your-text-domain\' )
),
array(
\'value\' => \'hockey\'
\'label\' => __( \'Hockey\', \'your-text-domain\' )
)
);
if ( $submitted ) {
echo __( \'The form has been submitted!\', \'your-text-domain\' );
}
echo \'<form action="#" method="post">\';
foreach ( $options as $option ) {
echo \'<input type="checkbox" \'
. \'value="\' . $option[\'value\'] . \'" \'
. \'name="types[]" \'
. \'id="types_\' . $option[\'value\'] . \'"\';
if ( $submitted && in_array( $option[\'value\'], $_POST[\'types\'] ) ) {
echo \' checked="checked"\';
}
echo \' /><label for="types_\' . $option[\'value\'] . \'">\'
. $option[\'label\'] . \'</label>\';
}
echo \'</form>\';
}
/**
* Constructor
*
* @since 1.0
* @access public
*/
public function __construct() {
add_shortcode(
\'wpse_161632_sports_selection_form\',
array( $this, \'form_handler\' )
);
}
}
endif; // class exists
$wpse_161632 = new WPSE_161632;
?>