Obtaining Wordpress custom widget options using AJAX - ajax

I am writing a custom widget on WordPress. This custom widget will be used to display a specific item belonging to a Custom Field that I have also set up.
With the code blow, I'm having some troubles:
public function form( $instance ) {?>
<?php
$args = array(
'hide_empty' => true,
'exclude' => 2,
);
$categories = get_categories($args); ?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'team' ) ); ?>">Team:</label>
<select id="<?php echo esc_attr( $this->get_field_id( 'team' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'team' ) ); ?>" value="<?php echo $instance['team']; ?>" style="width:100%;" >
<?php
foreach($categories as $team) {
echo '<option value="'.$team->term_id.'">'.$team->name.'</option>';
}
?>
</select>
</p>
<?php
$args_players = array(
'post_type' => 'player'
);
$players = get_posts($args_players);
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'player' ) ); ?>">Player:</label>
<select id="<?php echo esc_attr( $this->get_field_id( 'player' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'player' ) ); ?>" value="<?php echo $instance['player']; ?>" style="width:100%;" >
<?php
foreach($players as $player) {
echo '<option value="'.$player->ID.'">'.$player->post_title.'</option>';
}
?>
</select>
</p>
<?php
}
The Custom Post Field is called "Player" and the idea is to display a "Featured Player" on the sidebar. Each "Player" belongs to a "Team", that is selected in this specific fragment of the previous code:
$args = array(
'hide_empty' => true,
'exclude' => 2,
);
$categories = get_categories($args); ?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'team' ) ); ?>">Team:</label>
<select id="<?php echo esc_attr( $this->get_field_id( 'team' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'team' ) ); ?>" value="<?php echo $instance['team']; ?>" style="width:100%;" >
<?php
foreach($categories as $team) {
echo '<option value="'.$team->term_id.'">'.$team->name.'</option>';
}
?>
</select>
</p>
This works as expected, but the other fragment of the code should gather "Players" from the selected "Team".
I have tried several options but I can't seem to find something that actually works, and I was wondering if I could use AJAX to achieve this.
Thanks in advance!

you can access the widget's options like this:
public function ajax_call(){
$instance = $this->get_settings();
wp_send_json(array(
'instance' => $instance
));
}

Related

How to display all images fields on custom page with post type

I'm trying to loop through the fields of ACF to display all the images of a post type and a specific category
I give a practical example:
I have an ACF image field (image_of_project) and I want to view all the images uploaded in a post type (projects) associated with XYZ category
Now I created this loop:
'
$loop = new WP_Query( array(
'post_type' => 'projects',
'posts_per_page' => 9,
) );
while ( $loop->have_posts() ) : $loop->the_post();
$images = get_field('image_of_project');
if( $images ): ?>
<?php foreach( $images as $image ): ?>
<div class="item">
<a href="<?php echo get_permalink( $post->ID ); ?>" target="_blank">
<?php echo wp_get_attachment_image( $image ); ?>
</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php endwhile; ?>
'
The images are displayed but I do not understand why it duplicates me every single image and does not show me only the images of linked to a specific category.
Thanks to anyone who will help me on this mission!
For those interested in the feature, here’s how it worked for me.
function.php
// Loop Gallery Cat1
function my_custom_gallery_cat1() {
query_posts(array(
'post_type' => 'gd_project',
'orderby' => 'rand',
'posts_per_page' => 10,
'tax_query' => array(
array (
'taxonomy' => 'gd_projectcategory',
'field' => 'slug',
'terms' => 'example-terms',
)
),
));
?> <div class="masonry">
<?php
while (have_posts()) : the_post();
$image_field = get_field('image');
$image_url = $image_field['url'];
$image_alt = $image_field['alt']; ?>
<div class="grid-item">
<a href="<?php echo get_permalink( $post->ID ); ?>" target="_blank">
<img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($image_alt); ?>" />
<h4><?php the_field( 'title' ); ?></h4>
</a>
</div>
<?php endwhile; ?>
</div> <?php
}
add_shortcode('example-terms', 'my_custom_gallery_cat1');
single-example.php
<div class="container-fluid">
<div class="row">
<?php echo do_shortcode('[categoria]');?>
</div>
</div>

get selected form_dropdown codeigniter from database

i am new with codeigniter, and i am trying to set selected value from database,
this code doesn't work,
<?php
$options = array(
'one' => 'one',
'two' => 'two',
);
$selected = $teach->number;
echo form_dropdown('number', $options, $selected);
?>
but when i try to manual, it work.
<?php
$options = array(
'one' => 'one',
'two' => 'two',
);
$selected = 'one';
echo form_dropdown('number', $options, $selected);
?>
I don't know why,
Any advice would be great. Thanks
this my controller
public function index() {
$this->load->helper('url');
$id = $this->uri->segment(3);
$this->data['teach'] = $this->EditTeachModel->getPosts(); // calling Post model method getPosts()
$this->data['singleTeach'] = $this->EditTeachModel->getPostsId($id); // calling Post model method getPosts()
//view
$this->load->view('edit_teach', $this->data); // load the view file , we are passing $data array to view file
}
public function update(){
$id = $this->input->post('kd');
$this->load->library('form_validation');
$data = array(
'kd' => $this->input->post('kd'),
'name' => $this->input->post('name'),
'date' => $this->input->post('date'),
'number' => $this->input->post('number'),
'pass' => $this->input->post('pass')
);
$this->EditTeachModel->updatePosts($id, $data);
$this->index();
}
This my model
public function getPosts(){
$this->db->from('teach');
$query = $this->db->get();
return $query->result();
}
public function getPostsId($data){
$this->db->select('*');
$this->db->from('teach');
$this->db->where('kd', $data);
$query = $this->db->get();
$result = $query->result();
return $result;
}
public function updatePosts($id, $data){
$this->db->where('kd', $id);
$this->db->update('teach', $data);
}
this my view
<?php foreach($singleTeach as $teach) {?>
<form method="post" action="<?php echo base_url() . "edit_teach/update"?>">
<div class="card-body"><td>
<div class="row">
<div class="col-6">
<div class="form-group">
<label id="kd">Kode :</label>
<input type="text" id="kd" name="kd" class="form-control" value="<?php echo $teach->kd; ?>">
</div>
<div class="form-group">
<label id="name">Nama:</label>
<input type="text" id="name" name="name" class="form-control" value="<?php echo $teach->name; ?>">
</div>
<div class="form-group">
<label id="date">Date :</label>
<input type="text" id="date" name="date" class="form-control" value="<?php echo $teach->date; ?>">
</div>
<div class="form-group">
<?php echo form_label('Number '); ?> <?php echo form_error('number'); ?>
<?php
$options = array(
'one' => 'one',
'two' => 'two',
);
$selected = $teach->number;
print_r($teach);
echo form_dropdown('number', $options, $selected);
?>
</div>
<div class="form-group">
<label id="pass">Password :</label>
<input type="text" id="pass" name="pass" class="form-control" value="<?php echo $teach->pass; ?>">
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<?php echo form_submit(array('id' => 'submit','class'=> 'btn btn-primary', 'value' => 'Submit')); ?>
</div>
</form>
<?php } ?>

Codeigniter 3 blog application: update() method deletes thumbnail

I am working on a basic blog application in Codeigniter 3.1.8.
There is a create post and an update post functionality.
When a post is created, there is the option to upload a post thumbnail, else a default image is displayed. In the post controller there is the method for creating posts:
public function create() {
// More code here
if($this->form_validation->run() === FALSE){
$this->load->view('partials/header', $data);
$this->load->view('create');
$this->load->view('partials/footer');
} else {
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'default.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->Posts_model->create_post($post_image);
redirect('posts');
}
}
There is a method for updating posts:
public function update() {
// Form data validation rules
// irrelevant for the question suppressed
$id = $this->input->post('id');
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
$data = array('upload_data' => $this->upload->data());
$this->upload->do_upload();
$post_image = $_FILES['userfile']['name'];
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image);
redirect('posts/post/' . $id);
} else {
$this->edit($id);
}
}
In the Posts_model model:
public function update_post($id, $post_image) {
$data = [
'title' => $this->input->post('title'),
'description' => $this->input->post('desc'),
'content' => $this->input->post('body'),
'post_image' => $post_image,
'cat_id' => $this->input->post('category')
];
$this->db->where('id', $id);
return $this->db->update('posts', $data);
}
The edit post view:
<?php echo form_open_multipart(base_url('posts/update')); ?>
<input type="hidden" name="id" id="pid" value="<?php echo $post->id; ?>">
<div class="form-group <?php if(form_error('title')) echo 'has-error';?>">
<input type="text" name="title" id="title" class="form-control" placeholder="Title" value="<?php echo $post->title; ?>">
<?php if(form_error('title')) echo form_error('title'); ?>
</div>
<div class="form-group <?php if(form_error('desc')) echo 'has-error';?>">
<input type="text" name="desc" id="desc" class="form-control" placeholder="Short decription" value="<?php echo $post->description; ?>">
<?php if(form_error('desc')) echo form_error('desc'); ?>
</div>
<div class="form-group <?php if(form_error('body')) echo 'has-error';?>">
<textarea name="body" id="body" cols="30" rows="5" class="form-control" placeholder="Add post body"><?php echo $post->content; ?></textarea>
<?php if(form_error('body')) echo form_error('body'); ?>
</div>
<div class="form-group">
<select name="category" id="category" class="form-control">
<?php foreach ($categories as $category): ?>
<?php if ($category->id == $post->cat_id): ?>
<option value="<?php echo $category->id; ?>" selected><?php echo $category->name; ?></option>
<?php else: ?>
<option value="<?php echo $category->id; ?>"><?php echo $category->name; ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<label for="postimage">Upload an image</label>
<div class="form-group">
<input type="file" name="userfile" id="postimage" size="20">
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
The problem with the update() method is that, when editing a post, unless I replace it's existing thumbnail with a new one (in other words, if I let the file upload field empty), results in leaving the post without a thumbnail:
<img src="http://localhost/ciblog/assets/img/posts/">
What I have tried (not the best idea, I admit) is to fetch the name pg the file already existing in the posts table this way:
$data['post'] = $this->Posts_model->get_post($id);
$post_image = $data['post']->post_image;
But it gives the error Trying to get property of non-object.
What am I doing wrong?
Solved it:
In the edit post form, I have added an input of type hidden above the file input, in order to "capture" the posts image from the database:
<input type="hidden" name="postimage" id="postimage" value="<?php echo $post->post_image; ?>">
<label for="postimage">Upload an image</label><div class="form-group">
<input type="file" name="userfile" id="postimage" size="20">
</div>
In the Posts controller, I have replaced
$data = array('upload_data' => $this->upload->data());
$this->upload->do_upload();
$post_image = $_FILES['userfile']['name'];
with:
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
The code above means: if no new image is uploaded, write the name of the existing one in the posts table again, instead of writing nothing. If instead a new photo is uploaded, write the name of the new photo.

How add create AdditionalActionBlockHtml into massactions in category products grid in magento?

How add create AdditionalActionBlockHtml into massactions in category products grid?
like this status
I founded getAdditionalActionBlockHtml in app/design/adminhtml/default/default/template/widget/grid/massaction.phtml
But I'm dont understand how it's work.
<div class="right">
<div class="entry-edit">
<?php if ($this->getHideFormElement() !== true):?>
<form action="" id="<?php echo $this->getHtmlId() ?>-form" method="post">
<?php endif ?>
<?php echo $this->getBlockHtml('formkey')?>
<fieldset>
<span class="field-row">
<label><?php echo $this->__('Actions') ?></label>
<select id="<?php echo $this->getHtmlId() ?>-select" class="required-entry select absolute-advice local-validation">
<option value=""></option>
<?php foreach($this->getItems() as $_item): ?>
<option value="<?php echo $_item->getId() ?>"<?php echo ($_item->getSelected() ? ' selected="selected"' : '')?>><?php echo $_item->getLabel() ?></option>
<?php endforeach; ?>
</select>
</span>
<span class="outer-span" id="<?php echo $this->getHtmlId() ?>-form-hiddens"></span>
<span class="outer-span" id="<?php echo $this->getHtmlId() ?>-form-additional"></span>
<span class="field-row">
<?php echo $this->getApplyButtonHtml() ?>
</span>
</fieldset>
<?php if ($this->getHideFormElement() !== true):?>
</form>
<?php endif ?>
</div>
<div class="no-display">
<?php foreach($this->getItems() as $_item): ?>
<div id="<?php echo $this->getHtmlId() ?>-item-<?php echo $_item->getId() ?>-block">
<?php echo $_item->getAdditionalActionBlockHtml() ?>
</div>
<?php endforeach; ?>
</div>
</div>
I decided this via add methods in massactions
public function addMassAction($observer)
{
$block = $observer->getEvent()->getBlock();
if(get_class($block) =='Mage_Adminhtml_Block_Widget_Grid_Massaction' && $block->getRequest()->getControllerName() == 'catalog_product')
{
$stores = Mage::getSingleton('adminhtml/system_config_source_store')->toOptionArray();
$block->addItem('export', array(
'label' => Mage::helper("prodestransl")->__("Export"),
'url' => Mage::helper('adminhtml')->getUrl('prod/adminhtml_export/run'),
'additional' => array(
'stores' => array(
'name' => 'stores',
'type' => 'select',
'class' => 'required-entry',
'label' => Mage::helper('catalog')->__('Stores'),
'values' => $stores
)
)
));
}
}

OUTPUGet street1 and street 2 Magento

How I can get street address 1 and street address 2 value. I create an extension and I want to get street address in Magento. In the block I have this function:
public function updateFormData() {
$data = $this->getData('form_data');
if (is_null($data)) {
/** #var array $formData */
$formData = Mage::getSingleton('customer/session')->getCustomerFormData(true);
$order = $this->getOrder();
$address = $order->getShippingAddress();
$customerData = [
'email' => $order->getCustomerEmail(),
'firstname' => $order->getCustomerFirstname(),
'lastname' => $order->getCustomerLastname(),
'city' => $order->getBillingAddress()->getCity(),
'country' => $order->getBillingAddress()->getCountry(),
'telephone' => $order->getBillingAddress()->getTelephone(),
'company' => $order->getBillingAddress()->getCompany(),
];
$data = new Varien_Object();
if ($formData) {
$data->addData($formData);
$data->setCustomerData(1);
}
$data->addData($customerData);
if (isset($data['region_id'])) {
$data['region_id'] = (int)$data['region_id'];
}
$this->setData('form_data', $data);
}
return $data;
}
and in the phtml file I add this:
<?php $_streetValidationClass = $this->helper('customer/address')->getAttributeValidationClass('street'); ?>
<li class="wide">
<label for="street_1" class="required"><em>*</em><?php echo $this->__('Street Address') ?></label>
<div class="input-box">
<input type="text" name="street[]" value="<?php echo $this->escapeHtml($this->getFormData()->getStreet(1)) ?>" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Street Address')) ?>" id="street_1" class="input-text <?php echo $_streetValidationClass ?>" />
</div>
</li>
<?php $_streetValidationClass = trim(str_replace('required-entry', '', $_streetValidationClass)); ?>
<?php for ($_i = 2, $_n = $this->helper('customer/address')->getStreetLines(); $_i <= $_n; $_i++): ?>
<li class="wide">
<div class="input-box">
<input type="text" name="street[]" value="<?php echo $this->escapeHtml($this->getFormData()->getStreet($_i)) ?>" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Street Address %s', $_i)) ?>" id="street_<?php echo $_i ?>" class="input-text <?php echo $_streetValidationClass ?>" />
</div>
</li>
<?php endfor; ?>
I try to add this 'street_1' => $order->getBillingAddress()->getData('street'),
But always street_1 address value is blank. I try to get all fields in the order success page.
OUTPUT:
<li class="wide">
<label class="required" for="street_1">
<div class="input-box">
<input id="street_1" class="input-text required-entry" type="text" title="Street Address" value="address1 address2" name="street[]">
</div>
</li>
<li class="wide">
<div class="input-box">
<input id="street_2" class="input-text " type="text" title="Street Address 2" value="" name="street[]">
</div>
</li>
$order->getBillingAddress()->getData('street') will return an array.
So you can access the data with:
$billingStreet = $order->getBillingAddress()->getData('street');
$billingStreet1 = $billingStreet[0];
$billingStreet2 = $billingStreet[1];
$billingStreet3 = $billingStreet[2];
edit: the code above is to get the billing address of an order, what I think you want now is actually the new address, the data set in the form. So this should give you the information you're after, as long as you put it before the $data = new Varien_Object(); line:
$streetArray = $data['street'];
$street1 = $streetArray[0];
$street2 = $streetArray[1];
so your function will be:
public function updateFormData() {
$data = $this->getData('form_data');
if (is_null($data)) {
/** #var array $formData */
$formData = Mage::getSingleton('customer/session')->getCustomerFormData(true);
$order = $this->getOrder();
$address = $order->getShippingAddress();
$streetArray = $data['street'];
$street1 = $streetArray[0];
$street2 = $streetArray[1];
$customerData = [
'email' => $order->getCustomerEmail(),
'firstname' => $order->getCustomerFirstname(),
'lastname' => $order->getCustomerLastname(),
'city' => $order->getBillingAddress()->getCity(),
'country' => $order->getBillingAddress()->getCountry(),
'telephone' => $order->getBillingAddress()->getTelephone(),
'company' => $order->getBillingAddress()->getCompany(),
'street_1' => $street1,
'street_2' => $street2
];
$data = new Varien_Object();
if ($formData) {
$data->addData($formData);
$data->setCustomerData(1);
}
$data->addData($customerData);
if (isset($data['region_id'])) {
$data['region_id'] = (int)$data['region_id'];
}
$this->setData('form_data', $data);
}
return $data;
}

Resources