WordPress WP_Query showing only first element in the array - loops

I am currently learning on WordPress plugin development and I am trying to build a short code for my plugin
my plugin is basically a custom post type called property which have 3 meta data boxs in it
price location and date of construction
and one taxonomy called property type which be setted at the backend with rent or sale
all of this works and if you put them in wordpress they will work
But my shortcode file does work properly the loop on the WP_Query should return all the post which I have made but instead its returning only the first element found in the WP_Query
Can anyone guide me or fix where I have mistaken please
thanks all
now my short code file name is: properties_post_type_shortcode.php
My plugin file name is: properties_post_type.php
code for properties_post_type_shortcode.php
<?php
add_shortcode('land_properties',function(){
$loop = new WP_Query(
array(
'post_type' => 'property_post',
'orderby' => 'title'
)
);
if ($loop->have_posts()){
$output = '<ul class="land_properties_list">';
$i=0;
while( $loop->have_posts() ){
$loop->the_post();
$meta=get_post_meta(get_the_id(),'' );
$output= '
<li>
<a href="' .get_permalink() . '">
' . get_the_title() . ' | '.
$meta['property_price'][0]. " " .
$meta['property_location'][0]. " " .
$meta['property_date'][0]. " " .
'
</a>
<div>' . get_the_excerpt() . '</div>
</li>
';
}
}
else {
$output="No lands added";
}
// $loop->wp_reset_postdata();
return $output;
});
code for properties_post_type.php
<?php
/*
* Plugin Name: properties_post_type
* Plugin URI: Have not be set yet
* Description: this plugin allow you to create custom post type property which you can be modified and edited
* Version: 1.0
* Author: Muhab Alwan
* Author URI: https://www.facebook.com/HaaaB
* License: A "Slug" license name e.g. GPL2
*/
class PROP_POST_TYPE{
//default contructor
public function __construct()
{
$this->register_post_type();
$this->taxonomies();
$this->metaboxes();
}
public function register_post_type()
{
$args= array(
'labels' => array(
'name'=> 'Properties',
'singular_value' => 'Property',
'add_new' => 'Add New Property',
'add_new_item' => 'Add New Property',
'edit_items' => 'Edit_Items',
'new_item' => ' Add New Items',
'view_item'=> 'View Item',
'search_items' => 'Search Items',
'not_found' => 'No Property Found',
'not_found_in_trash' => 'No Property Found In Trash'),
'query_var' =>'properties',
'rewrite' => array(
'slug' => 'property/'),
'public' => true,
'menu_position' => 80, // set postion in the backend menu
'menu_icon' => admin_url(). 'images/media-button-other.gif', // define an image for the prop
'supports' => array(
'title',
//'editor',
'excerpt',
//'custom-fields' when we need user to build their own meta box Not required in project
) // specify what wordpress types are custom post type support
);
register_post_type('property_post', $args );
}
public function taxonomies()
{
$taxonomies = array();
$taxonomies['property_type'] = array(
'hierarchical' => true,
'query_var' => 'movie_genere',
'rewrite' => array('slug' => 'prop/type'
),
'labels' => array(
'name'=> 'Properties Type',
'singular_value' => 'Property Type',
'add_new' => 'Add New Property Type',
'add_new_item' => 'Add New Property Type',
'edit_items' => 'Edit Properties Type',
'new_item' => ' Add New Properties Type',
'view_item'=> 'View Property Type',
'search_items' => 'Search Properties Type',
'popular_items' => 'Popular Properties Type',
'separate_items_with_comments' => 'Separate Property Type With Comments',
'add_or_remove_items' => 'Add Or Remove Properties Type',
'choose_from_most_used' => 'Choose From Most Used Properties Type'
)
);
$this-> register_all_taxonomies($taxonomies); // register all taxonomies build in this plugin
}
public function register_all_taxonomies($taxonomies)
{
// foreach is for registering many taxonomy
foreach ($taxonomies as $name=> $arr)
{
//register ( what the taxonomies name, array of the object type that we register ex post or page
register_taxonomy($name,array('property_post'),$arr );
}
}
public function metaboxes()
{
// FIRST PRICE META BOX
add_action('add_meta_boxes', function(){
//css id, title, cb func, page, priority level, call back func argum
add_meta_box('property_price','Property Price', 'property_price','property_post');
add_meta_box('property_location','Property Location', 'property_location','property_post');
add_meta_box('property_date','Date Of Construction', 'property_date','property_post');
});
//PRICE PROP
function property_price($post){
$price_length = get_post_meta($post->ID,'property_price', true);
?>
<p>
<label for="property_price"> :</label>
<input type="number" pattern="[0-9]+" size="50" class="widfat" name="property_price" id="property_price" value="<?php echo esc_attr($price_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_price']))
{
update_post_meta(
$id,'property_price',
strip_tags($_POST['property_price'])
);
}
});
// LOCATIO PROP
function property_location($post){
$location_length = get_post_meta($post->ID,'property_location', true);
?>
<p>
<label for="property_location"> :</label>
<input type="text" class="widfat" name="property_location" id="property_location" value="<?php echo esc_attr($location_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_location']))
{
update_post_meta(
$id,'property_location',
strip_tags($_POST['property_location'])
);
}
});
function property_date($post){
$dof_length = get_post_meta($post->ID,'property_date', true);
?>
<p>
<label for="property_date"> :</label>
<input type="date" class="widfat" name="property_date" id="property_date" value="<?php echo esc_attr($dof_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_date']))
{
update_post_meta(
$id,'property_date',
strip_tags($_POST['property_date'])
);
}
});
//third date of construction metaboxes
}
}
// initialization essential to build a cust post
add_action('init', function(){
new PROP_POST_TYPE();
include dirname(__FILE__). '/properties_post_type_shortcode.php';
});

To query all posts, add the following to the args of WP_Query:
'posts_per_page' => -1
Your code:
$loop = new WP_Query( array(
'post_type' => 'property_post',
'orderby' => 'title',
'posts_per_page' => -1
) );

Related

Unexpected field 'g-recaptcha-response' in POST data on CakePHP 3

I have created a site using CakePHP 3. I have static page which has contact us form something like this:
inside contactus.ctp:
<?=$this->Form->create(); ?>
<?=$this->Form->hidden('form_type',['value' => 'contact']) ?>
<?=$this->Form->input('name',[
'label' => false,
'placeholder' => 'Your Full Name',
'required' => true
]); ?>
<?=$this->Form->input('email',[
'label' => false,
'placeholder' => 'Your Email',
'type' => 'email',
'require' => true
]); ?>
<?=$this->Form->textarea('message',[
'placeholder' => 'Your message...'
]) ?>
<?= $this->Recaptcha->display()?>
<button>Submit Query!</button>
<?=$this->Form->end(); ?>
Using the following link I created Recaptcha:
https://github.com/agiletechvn/Recaptcha
Just beside the Submit button I have Recaptcha.
In the pageController I have the submit check happening:
if($this->request->is(['post']) && $this->request->data('form_type') == 'contact'){
$name = $this->request->data('name');
$email = $this->request->data('email');
$message = $this->request->data('message');
if(!$name){
$this->Flash->set('Please enter a name' . $name,['element' => 'error']);
} elseif (!$email || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$this->Flash->set('The email you entered is invalid',['element' => 'error']);
} elseif(!$message){
$this->Flash->set('Message cannot be blank',['element' => 'error']);
} else {
if($this->Recaptcha->verify()) {
$emailObj = new Email();
$emailObj
->from(['contactus#mydomain.com' => 'Developer'])
->replyTo([$email => $name])
->to(['contactus#contactus.com'])
->template('pages/contactus')
->viewVars([
'quickAction' => [
'description' => 'Contact form',
'action' => "from: $name"
],
'name' => 'contactus#mydomain.com',
'senderName' => $name,
'email' => $email,
'message' => $message
])
->subject('Contact email from ' . $name)
->send();
$this->Flash->set('Your message has been sent', ['element' => 'success']);
}
$this->Flash->error(__('Please pass Google Recaptcha first'));
}
If I click submit button I get:
Unexpected field 'g-recaptcha-response' in POST data
I moved the reCaptcha code outside the form. Everything works correctly but the captcha but is sitting outside some random location like this:
How do I solve this issue?
This message can show if you are using CakePHP Security Component, and this component does not recognize one of your form fields. You should unlock this field using:
$this->Form->unlockField('g-recaptcha-response');
More info: CakePHP 3.x Security Component

Form Dropdown Not Registering in Codeigniter

I have created a registration form that has a dropdown field, but I am unable to get it to link into the database to register the selection. I have form validation turned on, but it keeps saying that no value has been selected.
My other inputs work, as they're user entered. However, the values in this dropdown do not register as any value. Any assistance would be appreciated.
Thanks!
View
<div class = "form-group">
<?php echo form_label('Mobile Carrier'); ?><br/><!--Form Label-->
<?php
$data = array(
'None' => 'None',
'att' => 'AT&T',
'verizon' => 'Verizon',
'sprint' => 'Sprint',
'tmobile' => 'T-Mobile'
);
?>
<?php echo form_dropdown('Mobile Carrier', $data, 'None'); ?>
Controller
public function register(){
$this->form_validation->set_rules('mobile_carrier', 'Mobile Carrier', 'required'); }
User Model
public function create_user(){
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'phone_number' => $this->input->post('phone_number'),
'mobile_carrier' => $this->input->post('mobile_carrier'),
'username' => $this->input->post('username'),
'password' => $encrypted_pass
);
$insert_data = $this->db->insert('users', $data);
return $insert_data;
}
you are assigning the wrong name attribute when creating the dropdown list:
<?php echo form_dropdown('Mobile Carrier', $data, 'None'); ?>
the name attribute must match your $this->input->post('mobile_carrier') in your model. so the correct use would be:
<?php echo form_dropdown('mobile_carrier', $data, 'None'); ?>
more information: https://www.codeigniter.com/userguide3/helpers/form_helper.html, scroll to form_dropdown([$name = ''[, $options = array()[, $selected = array()[, $extra = '']]]])

Dynamic Array Options in WordPress Plugin Settings Class

For one of my plugins I need to add a multiselect to my plugin options, but the options in the multiselect are dynamic (autogenerated from the given site's user roles).
$this->settings['manageraccess'] = array(
'section' => 'manager',
'title' => __('Manager Mode Access'),
'desc' => __(''),
'type' => 'manageraccess',
'std' => '',
'dflt' => '',
'helplink'=> 'yes',
'submit' => 'yes'
);
Normally I would add:
'choices' => array(
'op1' => 'Option 1',
'op2' => 'Option 2',
),
to the above array, but I need to generate them dynamically, like I do in my select box. My field case looks like this:
case 'manageraccess':
global $wp_roles;
$all_roles = $wp_roles->roles;
$editable_roles = apply_filters('editable_roles', $all_roles);
echo '<select multiple="multiple" class="select chozed-select' . $field_class . '" name="myplugin_options[' . $id . '][]" data-placeholder=" ">';
foreach($editable_roles as $role=>$theroles){
echo '<option value="' . esc_attr($role) . '" '.selected($options[$id], $role, false) . '>'.$wp_roles->role_names[$role].'</option>';
}
echo '</select>' . $helplink;
if ($desc != '')
echo '<br /><div class="ssfa-description">' . $desc . '</div>';
if ($submit != null)
echo '<br /><br /><br />'.$submit;
break;
Well I figured it out.
public function get_settings(){
global $wp_roles;
$this->settings['managertest'] = array(
'section' => 'manager',
'title' => __('Manager Mode Access'),
'desc' => __(''),
'type' => 'multi_select',
'std' => '',
'dflt' => '',
'choices' => $wp_roles->role_names,
'helplink'=> 'yes',
'submit' => 'yes'
);

CakePHP, Google Charts Plugin and JsHelper

i wish select an element of dropdownlist (choose a Project) and with JSHELPER (ajax) update the GRAPH that show statistics of this Project.
I can choose the Project and through the 'POST' I can generate the array graph, but i cannot show the GRAPH. I tested without JSHELPER and show my Graph.
MY VIEW CODE:
<b>ESCOLHA O PROJETO: </b>
<?php
echo $this->Form->select('projects', array($projects), array('multiple' => false,
'class' => 'span2',
'id' => 'projectsTest'));
?>
</br>
<div id="chart_div" >
</div>
<?php
$this->Js->get('#projectsTest')->event('change', $this->Js->request(array(
'controller' => 'Registos',
'action' => 'timePerProjectIssueTypeChart'
), array(
'update' => '#chart_div',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data' => $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
)));
?>
MY VIEW TIME_PER_PROJECT_ISSUE_TYPE_CHART
<div id="chart_div" >
<?php
echo $this->GoogleChart->createJsChart($timePerProjectIssueTypeChart);
?>
</div>
CONTROLLER
function timePerProjectIssueTypeChart() {
if (!empty($this->request->data['projects'])) {
$id_project = $this->request->data['projects'];
$totalProject = $this->timeSpentPerProjectSpecific(10001, 'Registo.issuetype');
$timeSpent = $this->totalTimeSpentPerProject(10001);
//Setup data for chart
$timePerProjectIssueTypeChart = new GoogleChart();
$timePerProjectIssueTypeChart->type("PieChart");
$timePerProjectIssueTypeChart->options(array('title' => "Percentagem de Tempo (horas) investido em cada Tarefa",
'height' => 300, 'width' => 500));
$timePerProjectIssueTypeChart->columns(array(
//Each column key should correspond to a field in your data array
'issuetype' => array(
'type' => 'string',
'label' => 'Tipo Tarefa'
),
'tempoGasto' => array(
'type' => 'time',
'label' => '% horas'
)
));
//You can also use this way to loop through data and creates data rows:
foreach ($totalProject as $row) {
if ($timeSpent[0][0]['tempogasto'] != 0) {
$percentagemTempoGasto = ($this->timeToHour($row[0]['tempogasto']) / $timeSpent[0][0]['tempogasto']) * 100;
} else {
$percentagemTempoGasto = 0;
}
if (!empty($row['IssueType'])) {
$timePerProjectIssueTypeChart->addRow(array('tempoGasto' => $percentagemTempoGasto, 'issuetype' => $row['IssueType']['pname']));
} else {
$timePerProjectIssueTypeChart->addRow(array('tempoGasto' => $percentagemTempoGasto, 'issuetype' => 'Sem tarefa'));
}
}
//Set the chart for your view
$this->set('totalProject', $totalProject);
$this->set('timeSpent', $timeSpent);
$this->set(compact('timePerProjectIssueTypeChart'));
}
}
I do not put the code of the controllers, because individually tested and are working.
Thanks
Teste com ajax, sem o JS helper:
$(document).ready(function() {
$("#projectsTest").change(function(){
$.ajax({
type: 'POST',
data: { projects: $('#projectsTest').val()},
url: 'timePerProjectIssueTypeChart',
success: funcion() {
$("chart_div").load('timePerProjectIssueTypeChart');
}
})
})
});
E não esqueça de colocar $this->layout = false no controller

Matching data from a drop down menu in add.cpt to view.ctp

Title seems a bit odd as I am trying to find way's to explain my dilema in layman's terms.
What I am trying to achieve is is from what I can gather, fairly simple but.. I just can't seem to place my finger on it.
I have a drop down selection menu which users can select a country of residence which resides in a helper - example below:
class CountryListHelper extends FormHelper {
var $helpers = array('Form');
function select($fieldname) {
$list = $this->Form->input($fieldname , array(
'type' => 'select', 'label' => 'Country of Residence', 'options' => array(
'' => 'Please select a country',
'AF' => 'Afganistan',
'AL' => 'Albania',
'DZ' => 'Algeria',
.................
),
'error' => 'Please select a country'));
return $this->output($list);
}
}
in the add.ctp:
<?php echo $this->CountryList->select('country');?>
Pretty simple stuff - on save it writes the acronym to the country field.
My issue is.. When pulling the data to view.ctp, how would I go about displaying the full country name as apposed to the acronym saved in the database without having to write the entire list down in view.ctp and matching the acronym to Country name there..
<dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Country of Residence'); ?></dt>
<dd<?php if ($i++ % 2 == 0) echo $class;?>>
<?php echo $user['User']['country']; ?>
</dd>
Any and all help is very much appreciated!
Add a new function to the helper that returns the full name of the country.
class CountryListHelper extends FormHelper {
var $helpers = array('Form');
var $countryList = array(
'AF' => 'Afganistan',
'AL' => 'Albania',
'DZ' => 'Algeria',
.................
);
function select($fieldname) {
$list = $this->Form->input($fieldname , array(
'type' => 'select', 'label' => 'Country of Residence',
'options' => $this->countryList,
'empty' => 'Please select a country',
'error' => 'Please select a country'));
return $this->output($list);
}
function fullName( $abbr ) {
return $this->countryList[ $abbr ];
// + error checking
}
}

Resources