I have an options panel in my WordPress theme with several text fields e.g. project title, project description, etc.
case 'text':
$val = $value['std'];
$std = get_option($value['id']);
if ( $std != "") { $val = $std; }
$output .= '<input class="" maxlength="12" name=""'. $value['id'] .'" id="'. $value['id'] .'" type="'. $value['type'] .'" value="'. $val .'" />';
break;
As the above code shows... I currently have my max length for the text fields as 12, but I would like to have a max length to be different for each of the text fields. How can I do this?
Define an array containing the fields and their corresponding maxlength values.
(I've used field names, but you could also use an Id number)
E.g: field_name => max_length_for_that_field
$maxFieldLengths = array(
'project_title' => 12, //project title has 12 max length
'project_description' => 100 //project description has 100 max length
);
Identify which text field (input) you are currently building and use that identifier to reference your maxFieldLengths array.
case 'text':
...
$field_name = // Identify the current field here;
$output .= '<input class="" maxlength="'. $maxFieldLengths[$field_name] .'" etc .....' />
break;
Note: From your code sample it's not 100% clear how you identify the field you are currently building. You could, for example, use something like:
...
$field_name = getFieldFromId($value['id']);
Related
I am populating Gravityforms fields using the functions.php from my template and it works like a charm, but I have one field that is ... a challenge. I have been able to populate the choices from my database just fine, but with the functions.php I cannot control the content of the display area of the field so that I can, for example, add a title or header for each category. Is there a way to programattically adjust the display here's an example of what im hoping to accomplish
RadioButton Choice (Field ID 21)
Dark Colors (category title)
maroon (choice 1)
navy blue (choice 2)
black (Choice 3)
Standard Colors (Category Title)
Red (choice 4)
blue (choice 5)
gray (Choice 6)
Light Colors )Category Title)
pink (choice 7)
sky blue (choice 8)
white (Choice 9)
I am just looking for a way to add the category title between the choices. My DB Query has the categories as part of the response, but the only option I have to populate choices to to feed an array.
I have seen where I can add additional Gravityform fields and have them controlled by the same "single select" radio button option, but the categories involved change based on the DB query I call to dynamically populate the choices and could range from 1 category to 10, which will not have correlating fields in the form itself, as this is all under a single radio-button field.
Any thoughts would be appreciated.
I was able to use the link I posted in my comment to provide a solution. As part of my "choices"
here is the function for the Pre-Render to populate choices. In this case I am populating a radio-button field with product images instead of default radio buttons
add_filter('gform_pre_render_1', 'populate_choices');
function populate_choices($form) {
global $wpdb;
// Now to get a list of the products I want to include on this radio-button
$dataQ = "
SELECT category, product_id, product_name
FROM product_table
WHERE product_type = 'whatever I am looking for'
ORDER BY category, product_name ASC
";
$dataR = $wpdb->get_results($dataQ);
$dataList = array();
// get current protocol to use in Product Images
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
// Rebuild URL for use with product image graphics
$productImageUrl = $protocol.$_SERVER['HTTP_HOST'].'/wp-content/product_images/';
// Generate list of choices for the radio-button, along with category headers
foreach ($form['fields'] as $field) {
if ($field->id == '32') { // 32 My specific radio-button field
$category = "";
foreach ($dataR as $data) {
if ($category != $data->category) {
// If I hit a new category, add the "header" item to the "choices" list with a unique search item to identify it, in this case "###"
$category = $data->category;
$dataList[] = array(
'text' => '#'.$category."#",
'value' => ''
);
}
$productImage = str_replace(" ","",strtolower($data->product_name)).".jpg";
$productID = $data->product_id;
$dataList[] = array(
'text' => $data->product_name,
'value' => $productID,
'isSelected' => false,
'price' => '0.00',
'imageChoices_image' => $productImagehUrl.$productImage
);
}
$field->choices = $dataList;
}
}
}
I then added a specific field modifier to update the "#category#" choice elements with html to make the category names show up.
// numbers after filter = "1" for form ID 1, "32" for field ID 32
add_filter('gform_field_choice_markup_pre_render_1_32', function( $choice_markup, $choice) {
if ( strpos( $choice['text'], '#' ) === 0 ) {
$categoryName = str_replace("#","",$choice['text']);
$choice_markup = '
<li style="width:100%;text-align:left;">
<span style="color:#000000;font-weight:bold;font-size:18px;">
<br>
'.$categoryName.'
</span>
</li>
';
}
return $choice_markup;
}, 10, 2);
The method OpenMods that you see below, is supposed to take an array generated by an fgetcsv function, and put it into an HTML table. __construct is supposed to, as is typically the case, define the attributes for the class, and shortcode is supposed to take two attributes from the shortcode, and if mods comes back, it is supposed to call another function in the class.
OpenMods did function when it was outside of a class, without the class attribute calls, so I'm fairly certain that isn't the source of my problem. My problem most likely lies within __construct and shortcode; However please don't overlook OpenMods as it may contain errors that are contributing to the problem, I'm just giving my estimation which isn't worth much since I'm having to ask to for help.
This is an example of the shortcode I'm trying to make work:
[priceguide file=’test.csv’ type=’mods’]
class CsvImporter
{
private $parse_header;
private $header;
private $delimiter;
private $length;
//--------------------------------------------------------------------
function __construct($parse_header=false, $delimiter="\t", $length=8000)
{
add_shortcode( 'priceguide', array( $this, 'shortcode' ) );
$this->parse_header = $parse_header;
$this->delimiter = $delimiter;
$this->length = $length;
}
//--------------------------------------------------------------------
public function shortcode($atts) {
$attributes = extract( shortcode_atts( array(
'file' => '',
'type' => '',
), $atts ));
if ($attributes['mods'])
{
$this->OpenMods($attributes['file']);
}
}
//--------------------------------------------------------------------
function OpenMods($file) {
ob_start();
$fp = fopen(plugin_dir_path( __FILE__ ) . $file , "r" );
if ($this->parse_header)
{
$header = fgetcsv($fp, $this->length, $this->delimiter);
}
// table header and search html
echo('<input type="text" class="search" id="search" placeholder="Search">');
echo('<br>');
echo('<table id="table"> <tr class="hidden">
<th><b>
Name</b>
</th>
<th><b>
Cheese</b>
</th>
<th><b>
Price</b>
</th>
<th><b>Vote</b>
</th>
</tr>
<tbody>');
// integer for drop down/price submit
$a = 1;
// set values for table data
while ($header !== FALSE) {
$name = $header[0];
$quanid = $header[2];
$table = $header[3];
unset($header[2]);
unset($header[3]);
$cssId = 'row-'.$a;
$a++;
//generate HTML
echo('<tr>');
foreach ($header as $index=>$val) {
echo('<td>');
echo htmlentities($val, ENT_QUOTES);
echo('</td>');
}
// query to get item prices
$sql = "SELECT ItemID, Price
FROM {$table}
WHERE ItemID = %d
GROUP BY Price
ORDER BY COUNT(*) DESC LIMIT 1";
global $wpdb;
$results = $wpdb->get_var( $wpdb->prepare( $sql, $quanid));
// put the results in the table
echo('<td>');
print_r($results);
echo('</td>');
// HTML for hidden row/price submission
echo('<td>
<button class="toggler" data-prod-cat="' . $cssId . '">Vote</button>
</td>');
echo('</tr>');
echo('<tr class="cat' . $cssId . ' hidden" style="display:none">');
echo('<td colspan="4" style="white-space: nowrap">Enter ' . $name . ' Price:
<form action="" name="form' . $quanid . '" method="post"><input type="text" id="' . $quanid . '" maxlength="4" name="' . $quanid . '" value="price_input" class="input" />
<button id="submit" name="submit" class="submit" type="submit" value="Submit">Submit</button></form>
<?php
?>
</td>
</tr>');
wp_nonce_field('price_input');
}
echo("</table>");
fclose($fp);
return ob_get_clean();
}
}
Based on OP comment, the problem is, the object can not created and in this case, __constructor() will not run, and add_shortcode( 'priceguide', array( $this, 'shortcode' ) ); will never triggered.
There are two solutions. One, if you are make the shortcode method to static, and add this in your functions.php file:
add_shortcode( 'priceguide', 'CsvImporter::shortcode' ) );
The second option, if you do not want to make it static if you instantiate an object from your class, before anythings happens. In your functions.php
add_action('init', 'my_init');
global $CsvImporter;
function my_init() {
global $CsvImporter;
$CsvImporter = new CsvImporter();
}
In this case, when no output send to the buffer, you create a new CsvImporter object, so the __construct() will run, so shortcode will registered.
I just converted a query that displays "bread crumbs" style navigation links to PDO:
function get_path($dbh,$node,$TopnavTable, $TopnavName) {
$stmt = $dbh->prepare("SELECT name FROM $TopnavTable WHERE $TopnavName = ?");
$stmt->bindValue(1,$node);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
$path = array_merge(get_path($pdo,$row['Parent'], $TopnavTable, $TopnavName), $path);
return $path ;
}
I also figured out how to display the results:
$Path2 = explode("/", $path);
$Path2[1] = ''.$Path2[1].'';
$Path2[2] = ''.$Path2[2].'';
$Path2[3] = '<span class="navHere"><b>'.$Path2[3].'</b></span>';
echo join( $Path2, ' > ' );
But there's a catch. The above works only if I'm working with an array consisting of three segments. For example, I'm viewing the URL MySite/Topics/Washington/Governor, which displays the following bread crumbs trail:
Topics > Washington > Governor
If I view MySite/Washington, it should display...
Topics > Washington
But I get an error message: Undefined offset: 3
So I'm trying to figure out how to make this work with any number of segments - 2, 3, 6, etc. Regardless of the number of segments, I'd like the last segment to be unlinked. (I'm going to further put it inside a span.) Does anyone have any tips?
When $path has only 3 members your code works. You have to modify your code to suit if different using array function count() & then loop through array.
$path ="Topics/Washington/Governor/Trash";
$Path2 = explode("/", $path);
$arrlength=count($Path2);
$html =''.$Path2[0].' > ';//First Member
for($x=1;$x<$arrlength-1;$x++) {//Between first & last
$html .= ''.$Path2[$x].' > ' ;
}
$html .= '<span class="navHere"><b>'.$Path2[$x].'</b></span>';//Last member
echo $html ;
RESULT for 3
Topics > Washington > Governor
for 2
Topics > Washington
I am using woocommerce for an eCommerce website. I want to add one more field in Login Regiser page. On this page there are three fields in registration (Email, Password and Re-enter password) and I want to add one more field for phone number.
Can anybody help me ? Thanks in Advance
http://wordpress.org/plugins/woocommerce/
If anyone else is curious on how to add additional fields to the login/register/any other account forms. You can achieve this quite easily since WooCommerce has added those to their templates folder. All you have to do is copy-paste the form you need to modify from plugins>woocommerce>templates>myaccount and drop it into your own theme. After which, you can add your extra fields and add any other functionality to make them work using http://docs.woothemes.com/document/hooks/
Hope this is of help to anyone who's been stuck on this.
I Use the "Register Plus Redux" plugin and use the "billing_phone" Database key to map to the correct field in the the User database. You can also have the user add other Information such as "'billing_address_1" and any others.
Best Regards
Marc
Old post, but this answer deals with the question as asked and provides a direct answer form the WordPress Codex
I have modified the code from the pages linked to act inline with the zipcode example that appears on the validation page. Each page within the codes used different examples, I just made them all the same.
Add the custom field
Plugin API/Action Reference/register form
The 'register_form' action hook is used to customize the built-in WordPress registration form.
Use in conjunction with 'registration_errors' (for validation) and 'register_post' (save extra data) when customizing registration.
WordPress MS Note: For Wordpress MS (Multi-Site), use the 'signup_header' action to redirect users away from the signup. (emphasis mine, took me a while to realise this)
Example
This example demonstrates how to add a new field to the registration form. Keep in mind that this won't be saved automatically. You will still need to set up validation rules and manually handle saving of the additional form fields.
add_action( 'register_form', 'myplugin_add_registration_fields' );
function myplugin_add_registration_fields() {
//Get and set any values already sent
$zipcode = ( isset( $_POST['zipcode'] ) ) ? $_POST['zipcode'] : '';
?>
<p>
<label for="user_extra"><?php _e( 'Extra Field', 'myplugin_textdomain' ) ?><br />
<input type="text" name="user_extra" id="user_extra" class="input" value="<?php echo esc_attr( stripslashes( $zipcode ) ); ?>" size="25" /></label>
</p>
<?php
}
link: https://codex.wordpress.org/Plugin_API/Action_Reference/login_form
Validation
You need to validate the user input (obviously) and should run that throughregistration_errors filter hook. Be mindful, the $errors variable may already be populated by other errors from the registration process. As in the examples, you would add your error to errors already contained therein.
Returning an Error
function myplugin_check_fields( $errors, $sanitized_user_login, $user_email ) {
$errors->add( 'demo_error', __( '<strong>ERROR</strong>: This is a demo error.', 'my_textdomain' ) );
return $errors;
}
add_filter( 'registration_errors', 'myplugin_check_fields', 10, 3 );
Validating a Custom Field
(this next section deals specifically with validation of the custom field)
Assuming you wanted to validate a postal code field that you have already created using the register_form hook, you might validate the field like so:
function myplugin_check_fields( $errors, $sanitized_user_login, $user_email ) {
if ( ! preg_match('/[0-9]{5}/', $_POST['zipcode'] ) ) {
$errors->add( 'zipcode_error', __( '<strong>ERROR</strong>: Invalid Zip.', 'my_textdomain' ) );
}
return $errors;
}
add_filter( 'registration_errors', 'myplugin_check_fields', 10, 3 );
link: https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_errors
finally, don't forget to save the custom field's data!
add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save( $user_id ) {
if ( isset( $_POST['zipcode'] ) )
update_user_meta($user_id, 'zipcode', $_POST['zipcode']);
}
link: https://codex.wordpress.org/Plugin_API/Action_Reference/user_register
A complete example
At the end of all this I ended up coming across a tutorial to do exactly this. In this example they are adding a First Name field:
//1. Add a new form element...
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
$first_name = ( ! empty( $_POST['first_name'] ) ) ? sanitize_text_field( $_POST['first_name'] ) : '';
?>
<p>
<label for="first_name"><?php _e( 'First Name', 'mydomain' ) ?><br />
<input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr( $first_name ); ?>" size="25" /></label>
</p>
<?php
}
//2. Add validation. In this case, we make sure first_name is required.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) && trim( $_POST['first_name'] ) == '' ) {
$errors->add( 'first_name_error', sprintf('<strong>%s</strong>: %s',__( 'ERROR', 'mydomain' ),__( 'You must include a first name.', 'mydomain' ) ) );
}
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
if ( ! empty( $_POST['first_name'] ) ) {
update_user_meta( $user_id, 'first_name', sanitize_text_field( $_POST['first_name'] ) );
}
}
https://codex.wordpress.org/Customizing_the_Registration_Form
I have a field -> tags text,
how do i output all entries tags? without duplicates
eg:
entry1 - tags: one, two, three
entry2 - tags: two, five
i want to be able to output all (one, two, three, five) without duplicates
so how do i find this in model/controller and output it to view?
do i use,
key::model()->findAll() ??
in controller in your action you need to put something like this
$data = key::model()->findAll();
$all = array();
foreach ($data as $d) {
$all = array_merge($all, explode(', ',$d->tags));
}
$all = array_unique($all);
$this->render('index', array(
'data' => $all,
));
and in view something like this
echo implode(', ',$data);
read this: http://php.net/manual/en/ref.array.php
and this:
http://www.yiiframework.com/doc/guide/1.1/en/basics.view
http://www.yiiframework.com/doc/guide/1.1/en/basics.controller