Wordpress : Update Loop with Form - ajax

I have a photo gallery I'm developing using WP as a means for content management. I'm relying heavily on some jQuery plugins to manage the UI styling and manipulation (via sorting). My problem is there are too many damn posts! 737, and each has a thumbnail which is displayed on the page. This inevitably bogs down any browser. Especially since the sorting plugin "clones" the images when it sorts them.
The posts are built using a Wp_query script;
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$post_per_page = 15; // (-1 shows all posts) SETS NUMBER OF IMAGES TO DISPLAY!
$do_not_show_stickies = 1; // 0 to show stickies
$args=array(
'post_type' => array ('post'),
'orderby' => 'rand',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => $post_per_page
);
$pf_categorynotin = get_post_meta($wp_query->post->ID, true);
if($pf_categorynotin){
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $pf_categorynotin,
'operator' => 'NOT IN'
)
); //category__in
}
$temp = $wp_query; // assign orginal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query($args);
//Begin LOOP #1
if( have_posts() ) :
echo '<ul id="applications" class="applications pf_item3">';
$r = 0;
while ($wp_query->have_posts()) : $wp_query->the_post();
$post_cat = array();
$post_cat = wp_get_object_terms($post->ID, "category");
$post_cats = array();
$post_rel = "";
for($h=0;$h<count($post_cat);$h++){
$post_rel .= $post_cat[$h]->slug.' ';
$post_cats[] = $post_cat[$h]->name;
}
$r++;
echo'<li data-id="id-'. $r .'" data-type="'.$post_rel.'" >';
if (get_post_meta($post->ID, 'port_thumb_image_url', true)) { ?>
<a class="tozoom" href="<?php echo get_post_meta($post->ID, 'port_large_image_url', true); ?>" rel="example4" title="<?php echo $post->post_title; ?>">
<img src="<?php echo get_post_meta($post->ID, 'port_thumb_image_url', true); ?>" class="portfolio_box" alt="<?php the_title(); ?>" width="199px" height="134px" /></a>
<?php } ?>
</li>
<?php endwhile ?>
</ul>
and the items are sorted by their html5 tags with a menu in the sidebar.
You can see it working here;
http://marbledesigns.net/marbledesigns/products
Right now it randomly loads 15 posts and displays them. I want to be able to reload posts based on my selection from the menu (via categories) and then update the list of images without refreshing the page. I want to be able to change not only which posts from which category are displayed, but also the posts per page as well.
I think AJAX is the way to do this, but I don't want to undo a whole bunch of code in the menu in order to get it working. Right now the menu is styled radio buttons. Isn't there a way I can take the same input from that form and update the parameters of the loop?
Looking for an efficient solution! Please help!

I'm going to abandon this method for reasons of time restriction. I've decided to use AJAX as a way to pull the list form the linked page and display it on the current one.
I followed this tutorial,
http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html
changed a couple names in the ajax.js script and it worked great!

Related

Yii2 update related model makes insert

Depending on this question: Yii2 updating two related models does not show data of the second. I have manged calling the related model InvoiceItems to the Invoices model it hasMany relation.
However, updating leads to insert new records in invoice_items table instead of updating the current related records to the invoices table.
I tried to add the id field of each InvoiceItems record in the _form view to solve this issue, but it still exist.
The following is actionUpdate of the InvoicesController:
public function actionUpdate($id)
{
$model = $this->findModel($id);
//$invoiceItems = new InvoiceItems();
$count = count(Yii::$app->request->post('InvoiceItems', []));
//Send at least one model to the form
$invoiceItems = [new InvoiceItems()];
//Create an array of the products submitted
for($i = 1; $i < $count; $i++) {
$invoiceItems[] = new InvoiceItems();
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//$invoiceItems->invoice_id = $model->id;
if (Model::loadMultiple($invoiceItems, Yii::$app->request->post())){
foreach ($invoiceItems as $item){
$item->invoice_id = $model->id;
//$item->id = $model->invoiceItems->id;
$item->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
}
else{
return var_dump($invoiceItems);
}
} else {
//$invoiceItems->invoice_id = $model->id;
$invoiceItems = $this->findInvoiceItemsModel($model->id);
return $this->render('update', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]);
}
}
This is the code of _form view of InvoicesController:
<div class="invoices-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'created')->textInput() ?>
<?= $form->field($model, 'type')->textInput(['maxlength' => true]) ?>
<hr />
<?php if (is_array($invoiceItems)): ?>
<?php foreach ($invoiceItems as $i => $item): ?>
<?= $form->field($item, "[$i]id")->textInput();?>
<?= $form->field($item, "[$i]item_id")->textInput();?>
<?= $form->field($item, "[$i]unit_id")->textInput();?>
<?= $form->field($item, "[$i]qty")->textInput();?>
<?php endforeach; ?>
<?php else: ?>
<?= $form->field($invoiceItems, "item_id")->textInput();?>
<?= $form->field($invoiceItems, "unit_id")->textInput();?>
<?= $form->field($invoiceItems, "qty")->textInput();?>
<?php endif; ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
The following screen shot, visually, demonstrates what I have got:
if you in update you don't need new record you should remove
this part
$count = count(Yii::$app->request->post('InvoiceItems', []));
//Send at least one model to the form
$invoiceItems = [new InvoiceItems()];
//Create an array of the products submitted
for($i = 1; $i < $count; $i++) {
$invoiceItems[] = new InvoiceItems();
}
The $invoiceItems you create in this way are obviuosly "new" and then are inserted ..for an update the model must to be not new..
You have already the related models to save they came from post.. and from load multiple
If you however need to manage new model (eg: because you added new record in wide form update operation) you can test
$yourModel->isNewRecord
and if this is new check then if the user have setted properly the related fields you can save it with
$yourModel->save();
otherwise you can simple discart.. (not saving it)
I am pretty sure that this code below of course fills a array named $invoiceItems with the submitted data.
if (Model::loadMultiple($invoiceItems, Yii::$app->request->post())){
foreach ($invoiceItems as $item){
$item->invoice_id = $model->id;
//$item->id = $model->invoiceItems->id;
$item->save(false);
}
}
But all $items have the scenario "insert" (could be that you allow the setting of the attribute 'ID' but normally this isn't allowed in the Gii generated code. and then you get "new items" whenever you save.
if you add a return var_dump($invoiceItems);after the loadMultiple you will see that only the safe attributes are filled with the submitted data.
You are also not validating them before saving, which is also kind of bad.
if (Model::loadMultiple($invoiceItems, Yii::$app->request->post()) && Model::validateMultiple($invoiceItems)) {
http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html
According to scaisEdge answer and this widget documentation. I could able to determine the problem solution.
Simply, in my code I neglected the relation between the two models, when I say:
$count = count(Yii::$app->request->post('InvoiceItems', []));
//Send at least one model to the form
$invoiceItems = [new InvoiceItems()];
The value of $invoiceItems should be obtained using the relation like the following:
$invoiceItems = $model->invoiceItems;
However, I still have another issue with adding new records to the related model InvoiceItems during the update.

Fetch images only from wordpress posts

In wordpress, when a post category (or tag) is clicked, all posts that match the clicked category (or tag) is returned, because of <?php the_content(); ?>
In my case, every post has an image in it, so how can I only fetch the images when a category (or tag) is clicked? I'm not familiar what code I need to use.
Update: I'm trying not to use plugins. My apologies for not mentioning that earlier. What I'm trying to achieve is something like The Sartorialist - All posts have images, click on any category (or tag) associated with any post and only images are fetched.
Update 2: I tried this:
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'full' );
echo '</li>';
}
}
?>
The only weird thing is, and I'm trying to figure out, another image from the media library also shows up, without it being in any of my posts.
I also found this plugin which is very close to what I want, but unfortunately it has to be in a separate page, not the in category page.
You can achieve this with something like this:
<?php
function getImage($num) {
global $more;
$more = 1;
$link = get_permalink();
$content = get_the_content();
$count = substr_count($content, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
$imgBeg = strpos($content, '<img', $start);
$post = substr($content, $imgBeg);
$imgEnd = strpos($post, '>');
$postOutput = substr($post, 0, $imgEnd+1);
$postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
$image[$i] = $postOutput;
$start=$imgEnd+1;
}
if(stristr($image[$num],'<img')) { echo ''.$image[$num].""; }
$more = 0;
}
?>
source

Codeigniter and Tank_auth sending validation to view not working

Hi I am new to Codeigniter but have hit a brick wall.
I am trying to see if a user already exists.
First I upload the data via a form to a controller which does its validation etc but breaks on only that issue. I managed to find where it breaks but cant fix it from there.
Prior to all this it querys the database finds there is in fact a match username and then reaches the snippet below
$errors = $this->tank_auth->get_error_message();
//find the correct error msg
foreach ($errors as $k => $v) $data['errors'][$k] =$this->lang->line($v);
//loop and find etc
$temp_mess = $data['errors'][$k];
//stores relevant stuff in the string
}
}
//echo $temp_mess; it outputs to the html so i can see it "says user exists"
$data['temp_mess'] = $tempmess; /// put this into a array
$this->load->view('layout', $data); ///send
}
}
Now for the view, it then calls the layout view etc but alas there is no output
$username1 = array(
'name' => 'username1',
'id' => 'username1',
'value' => set_value('username1'),
'maxlength' => $this->config->item('username_max_length', 'tank_auth'),
'size' => 30,
);
<?php echo form_open('register', $form_reg_id ); ?>
<fieldset>
<legend align="center">Sign up</legend>
<?php echo form_label('Username', $username1['id']); ?>
<?php echo form_input($username1); ?>
<?php $tempmess; ?>
<div class="error"><?php echo form_error($username1['name']); ?>
<?php echo isset($errors[$username1['name']])?$errors[$username1['name']]:''; ?>
<?php echo form_close(); ?>
</fieldset>
Thanks for any help on this
also could some one explain this line please. (for a really dumb person)
<?php echo isset($errors[$username1['name']])?$errors[$username1['name']]:''; ?>
Tank_auth automatically returns an error when the username exists. Juste have to check the errors array.

Magento - how to retrieve bundled option images

I've been working on my first magento deploy. Got a pretty customized theme built up... tackling some of the non-standard customizations now:
One of my primary product types is an office chair which I have set up as a bundled product. There are many options available for this product type (about 100 fabric options, arm style, lumbar, headrest etc) and I need to be able to show an image for each of these on the catalog/product/view page.
Being a bundled product (and I'll refrain from any discussion about whether this was the right product type - we went around in circles debating between a configurable and a bundled) - each product is assembled from a number of simple products (as options). These simple products can have images uploaded to them, and I've done so. I now want to retrieve the urls to those from the media folder...
After some hunting - these seem to be the essential elements:
theme/../template/catalog/product/view/options.phtml
<?php $_options = Mage::helper('core')->decorateArray($this->getOptions()) ?>
<dl>
<?php foreach($_options as $_option): ?>
<?php echo $this->getOptionHtml($_option) ?>
<?php endforeach; ?>
</dl>
theme/../template/bundle/catalog/product/view/type/bundle/option/select.phtml
<?php /* #var $this Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option_Select */ ?>
<?php $_option = $this->getOption(); ?>
<?php $_selections = $_option->getSelections(); ?>
I found finally found getSelections() in:
class Mage_Bundle_Model_Resource_Price_Index extends Mage_Core_Model_Resource_Db_Abstract
{ ...
/**
* Retrieve bundle options with selections and prices by product
*
* #param int $productId
* #return array
*/
public function getSelections($productId)
{
$options = array();
$read = $this->_getReadAdapter();
$select = $read->select()
->from(
array('option_table' => $this->getTable('bundle/option')),
array('option_id', 'required', 'type')
)
->join(
array('selection_table' => $this->getTable('bundle/selection')),
'selection_table.option_id=option_table.option_id',
array('selection_id', 'product_id', 'selection_price_type',
'selection_price_value', 'selection_qty', 'selection_can_change_qty')
)
->join(
array('e' => $this->getTable('catalog/product')),
'e.entity_id=selection_table.product_id AND e.required_options=0',
array()
)
->where('option_table.parent_id=:product_id');
$query = $read->query($select, array('product_id' => $productId));
while ($row = $query->fetch()) {
if (!isset($options[$row['option_id']])) {
$options[$row['option_id']] = array(
'option_id' => $row['option_id'],
'required' => $row['required'],
'type' => $row['type'],
'selections' => array()
);
}
$options[$row['option_id']]['selections'][$row['selection_id']] = array(
'selection_id' => $row['selection_id'],
'product_id' => $row['product_id'],
'price_type' => $row['selection_price_type'],
'price_value' => $row['selection_price_value'],
'qty' => $row['selection_qty'],
'can_change_qty' => $row['selection_can_change_qty']
);
}
return $options;
}
so we get back an array with selection_id, product_id, price_type etc... but nothing referring to the image url for that selection...
Given that:
class Mage_Catalog_Helper_Product extends Mage_Core_Helper_Url
{ ...
public function getImageUrl($product)
{
$url = false;
if (!$product->getImage()) {
$url = Mage::getDesign()->getSkinUrl('images/no_image.jpg');
}
elseif ($attribute = $product->getResource()->getAttribute('image')) {
$url = $attribute->getFrontend()->getUrl($product);
}
return $url;
}
I'm trying to build a js object with refs to each selection's image url kind of like so in theme/../template/bundle/catalog/product/view/type/bundle/option/select.phtml
var option_set_<?php echo $_option->getId() ?> = {};
<?php foreach ($_selections as $_selection): ?>
option_set_<?php echo $_option->getId() ?>._<?php echo $_selection->getSelectionId() ?> = '<?php echo $_selection->getImageUrl(); ?>';
<?php endforeach; ?>
But $_selection obviously isn't typed correctly because it just bounces me to the placeholder graphic.
Assuming these options can be typed as a Product (or somehow obtain the simple product from the selection_id, it seems like something like that can work. I'm not sure if that's exactly how I want to manage this feature, but if I can just get a stack of urls - then I'll be in business
Weirdly, the interwebs is basically silent on this subject. Apparently nobody needs to show images for their product options (or, rather, the only solutions are paid extensions - which will be a last resort).
How I can go about figuring this out?
Jesus tapdancing christ. Could Mage be any more complicated?
Update
Got this to work as such:
<?php echo $this->helper('catalog/image')->init($_selection, 'small_image')->resize(40,40); ?>
The answer I selected will also work fine, if anybody needs this fix.
The product_id in the $_selections represents the id of the selected simple product.
So all to do is:
take the product_id of the $_selections,
load the product by this product_id
give the resulting product object to Mage_Catalog_Helper_Product::getImageUrl.

Wordpress The Events Plugin wp_query not paginating

I've got an issue with Modern Tribe's "The Events Calendar" plugin not paginating properly. It displays the first page fine, but refuses to go to any secondary pages (using wp-pagenavi). Ideally, I'm trying to have it load via AJAX, but at this point pagination would be a miracle. I've exhausted an entire day here. Basically, this is the query:
<?php
$wp_query = new WP_Query();
$wp_query->query( array(
'post_type'=> 'tribe_events',
'eventDisplay' => 'upcoming',
'posts_per_page' => 5)
);
$max = $wp_query->max_num_pages;
$paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;
if ($wp_query->have_posts()) :
while ($wp_query->have_posts()) :
$wp_query->the_post();
?>
<li><!-- do stuff --> </li>
<?php
endwhile;?>
</ul>
<?php
endif;
wp_reset_query(); // important to reset the query
?>
There are quite a number of issues with your loop:
You say you're using wp_page_navi, however I'm not seeing any references to the plugin in any of your code. Also, you have list items being generated in your loop along with a closing ul tag, but I don't see any opening ul tag anywhere, which could also be contributing to some of your problems.
I'm also noticing in your list of arguments that you're trying to set 'eventDisplay' to 'upcoming'. 'eventDisplay' is not a valid WP_Query parameter. I'm guessing you probably have a registered Taxonomy of eventDisplay? If so, you will need to use Tax Query instead. I've removed this parameter in the example, but feel free to replace it when you're comfortable with setting the parameters you need.
Lastly, query arguments should be made when you call WP_Query, not through $query->query.
Here's something I came up with using standard Wordpress Paging and the arguments you have in your code. I'm not familiar with wp_page_navi, but this should help get you started on the right track:
<?php
global $paged;
$curpage = $paged ? $paged : 1;
$query = new WP_Query(array(
'post_type'=> 'tribe_events',
'paged' => $paged,
'posts_per_page' => 5
));
if ($query->have_posts()) :
?>
<ul>
<?php while ($query->have_posts()) : $query->the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; ?>
</ul>
<?php
echo '<div id="wp_pagination">';
echo '<a class="first page button" href="'.get_pagenum_link(1).'">«</a>';
echo '<a class="previous page button" href="'.get_pagenum_link(($curpage-1 > 0 ? $curpage-1 : 1)).'">‹</a>';
for($i=1;$i<=$query->max_num_pages;$i++)
{
echo '<a class="'.($active = $i == $curpage ? 'active ' : '').'page button" href="'.get_pagenum_link($i).'">'.$i.'</a>';
}
echo '<a class="next page button" href="'.get_pagenum_link(($curpage+1 <= $query->max_num_pages ? $curpage+1 : $query->max_num_pages)).'">›</a>';
echo '<a class="last page button" href="'.get_pagenum_link($query->max_num_pages).'">»</a>';
echo '</div>';
endif;
wp_reset_query();
?>
This will set your loop to display 5 post titles in your list. Below it will be a series of numbered links based on how many posts you have. When you click on a number, it reloads the page with its corresponding titles.
Let me know if this helps.

Resources