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
Related
I am creating products and images programmatically. The only thing that is not working is the "exclude from gallery" feature.
See http://snag.gy/QGhPg.jpg for details.
How would I set that in the code? My current code looks like that:
$product->addImageToMediaGallery($myImage, array('image','thumbnail','small_image'), false, false);
The flag is called disabled I think, not sure though.
Thanks!
For example, disable all images for a product
$product = Mage::getModel('catalog/product')->load(12345);
$images = $product->getMediaGalleryImages();
$attributes = $product->getTypeInstance(true)->getSetAttributes($product);
$mediaGalleryAttribute = $attributes['media_gallery'];
foreach ($images as $image) {
$mediaGalleryAttribute->getBackend()->updateImage($product, $image['file'], array('exclude' => true));
}
$product->save();
Try to use:
$product->addImageToMediaGallery($myImage, array('image','thumbnail','small_image'), false, true);
The last parameter should be set to true to exclude the image from gallery.
See: app/code/core/Mage/Catalog/Model/Product.php.
Try below code..first save product and insert image
$productid=10; // Product id of that product which image you want to update
//for remove existing Images
$loadpro=Mage::getModel('catalog/product')->load($productid);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApiItems = $mediaApi->items($loadpro->getId());
foreach($mediaApiItems as $item) {
$datatemp=$mediaApi->remove($loadpro->getId(), $item['file']);
}
$loadpro->save(); //before adding need to save product
//for add new images
$loadpro=Mage::getModel('catalog/product')->load($loadpro->getId());
$loadpro->addImageToMediaGallery($loadpro, array ('image','small_image','thumbnail'), true, false);
$mediaArray = array(
'thumbnail' => $oscProduct['products_image'],
'small_image' => $oscProduct['products_mediumimage'],
'image' => $oscProduct['products_largeimage'],
);
// Remove unset images, add image to gallery if exists
$importDir = Mage::getBaseDir('media') . DS . 'import/';
foreach ( $mediaArray as $imageType => $fileName ) {
$filePath = $importDir . $fileName;
if ( file_exists($filePath) ) {
try {
$product->addImageToMediaGallery($filePath, $imageType, false);
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Product does not have an image or the path is incorrect. Path was: {$filePath}<br/>";
}
}
Note: $imageType is not an array, as your counterpart is.
Edit: You only want one image, and to set it as each type. After you save the product with $product->save(), try something like the following, assuming you have set the image type already:
$product->setThumbnail($product->getImage());
$product->setSmallImage($product->getImage());
$product->save();
SCENARIO : I allow to create posts from front-end. The form also has four image upload fields. I use the code pasted below for image attachments and setting the post thumbnail.
//insert attachments
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); //you will need to comment out this line if you use my solution
return $attach_id;//you will need to comment out this line if you use my solution
}
The post-thumbnail/featured image that is set through this code is the LAST image that is uploaded. I tried a google search for "set post thumbnail from frontend wordpress" and grazed through a lot of articles but none came close to what I am asking here. Majority of threads I came across at SE in regards to front-end posting, either talks about setting the featured image or about multiple uploads. I have also checked all the suggested questions which were prompted, while I was writing this question just to make sure if it has been asked before.
If it matters, here is the html that is used in the form, pretty standard.
<input type="file" name="image-one" id="image-one"/>
<input type="file" name="image-two" id="image-two"/>
<input type="file" name="image-three" id="image-three"/>
REQUEST : It would be great if I could get a solution that helps to assign any chosen image-input-field as a featured-image but at this moment, at least what I need to set the FIRST image input to be set as a featured-image/post-thumbnail. Kindly suggest a solution.
Bottomline is that I do not have an issue with setting post-thumbnail
but question is about having a choice to choose any of the uploaded
images as post-thumbnail or at least the first image, instead of the
last image as set by the current code.
PROGRESS REPORT :
Never know if it would help in cracking this issue. But when I print_($newupload), I get the id eg. 54287 ,of the last-image-input attachment that is saved as post-thumbnail.
This thread suggests a way to set a featured-image with the first image found in the post so I thought of working on that idea. But the code does not seem to work either.
$attachments = get_children(array(
'post_parent' => $pid,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'ID'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($pid, $attachment->ID);
break;
}
FINAL WORD : The code in the progress report momentarily gets the job done for me, that is.. setting the first image-file-input as a featured-image/post-thumbnail and I am not even sure if this is the best way to do this. I am still looking for a solution which could give a flexibility to choose any image-input-field as a featured-image. If you decide to use this feature remember to comment out the second last and third last lines from the original code.
Saving a post_meta with _thumbnail_id as meta_key and the attach_id as meta_value won't make that image a featured image, you can use wp_insert_attachment that will help you a lot in this. Make sure you read the codex and the examples there. The function should be used in conjunction with wp_update_attachment_metadata() and wp_generate_attachment_metadata() this way your feature image will be created properly by wordpress.
EDIT:
I've looked over your code and I'm gussing it's easier to use it then my schetch in this case. I've added a file count and a parameter to insert_attachment. Check this code let me know what happens.
Example:
<?php
//insert attachments
if ($_FILES) {
array_reverse($_FILES);
$i = 0;//this will count the posts
foreach ($_FILES as $file => $array) {
if ($i == 0) $set_feature = 1; //if $i ==0 then we are dealing with the first post
else $set_feature = 0; //if $i!=0 we are not dealing with the first post
$newupload = insert_attachment($file,$pid, $set_feature);
$i++; //count posts
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail if setthumb is 1
if ($setthumb == 1) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
?>
We can set post featured image from frontend using following function,
simple you need to call this function
post_imgs_update($new_post_id);
after creating new post. and add following function in functions.php
if ( ! function_exists( 'post_imgs_update' ) ) :
function post_imgs_update($new_post_id) {
$data = array();
$attachment_ids = array();
// code for save featured image
if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){ // here nonce text is "image_upload" you need to add in form
$files = reArrayFiles($_FILES['files']);
if(!empty($_FILES['files'])){
//$i = 0;
$set_featured_img = 0 ;
foreach( $files as $file ){
if( is_array($file) ){
$attachment_id = upload_user_file( $file, basename($file['name']) );
if ( is_numeric($attachment_id) ) {
if ($set_featured_img == '0') {
set_post_thumbnail($new_post_id, $attachment_id);
$set_featured_img++;
$attachment_ids[] = $attachment_id;
}
else{
$attachment_ids[] = $attachment_id;
}
}
}
}
//add to array
$mediaurl = array();
foreach ($attachment_ids as $img_id) {
$imgurl = wp_get_attachment_url( $img_id );
$image_gallery[$img_id] = $imgurl;
}
update_post_meta( $new_post_id, '_stw_property_multi_images', $image_gallery); // 2nd arg field key
}
}
else {
$data['status'] = false;
$data['message'] = __('Nonce verify failed','realestate');
}
return $new_post_id;
}
endif;
if ( ! function_exists( 'reArrayFiles' ) ) :
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
endif;
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
$attachurlarray = array();
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
return $attach_id;
}
Trying to use this code to render a menu module on a custom template
jimport( 'joomla.application.module.helper' );
$module = JModuleHelper::getModule( 'menu' );
$attribs = array('style' => 'mainnav');
$module->params = "menutype=" .$mainmenu ."\nshowAllChildren=1";
echo JModuleHelper::renderModule($module, $attribs);
The menu only works if I have another menu module published, so I am sure this only needs a line of code to make it work without having to publish a menu module.
The menu exists, the module for this menu does not exist, I am trying to create it with this code.
Please help.
The code works fine I just had a small correction to make:
jimport( 'joomla.application.module.helper' );
$module = JModuleHelper::getModule( 'mod_menu' );
$attribs = array('style' => 'mainnav');
$module->params = "menutype=" .$mainmenu ."\nshowAllChildren=1";
echo JModuleHelper::renderModule($module, $attribs);
on the second line, the call should be to "mod_menu" and not just "menu", and this makes the code to work perfect :)
Why don't just use the include module?
<jdoc:include type="modules" name="mainnav" style="mainnav" />
This will allow you to publish whatever module you wan't in that position.
Otherwise the getModule function works like this:
JModuleHelper::getModule( 'position', 'title' );
According to the Joomla! API so you need to pass both parameters.
i use this code to render other module by id
$mod_id = $params->get('mod_id');
if ($type == 'logout' && $mod_id != ''){
$document = &JFactory::getDocument();
$renderer = $document->loadRenderer('module');
$db =& JFactory::getDBO();
if ($jVersion=='1.5') {
$query = 'SELECT id, title, module, position, params'
. ' FROM #__modules AS m'
. ' WHERE id='.intval($mod_id);
} else {
$query = 'SELECT id, title, module, position, content, showtitle, params'
. ' FROM #__modules AS m'
. ' WHERE m.id = '.intval($mod_id);
}
$db->setQuery( $query );
if ($mod = $db->loadObject()){
$file = $mod->module;
$custom = substr( $file, 0, 4 ) == 'mod_' ? 0 : 1;
$modu->user = $custom;
// CHECK: custom module name is given by the title field, otherwise it's just 'om' ??
$mod->name = $custom ? $mod->title : substr( $file, 4 );
$mod->style = null;
$mod->position = strtolower($mod->position);
echo $renderer->render($mod, array());
}
}
use this, 100%, render modules at this position.
<?php
$document = &JFactory::getDocument();
$renderer = $document->loadRenderer('modules');
$options = array('style' => 'xhtml');
$position = 'article-banners';
echo $renderer->render($position, $options, null);
?>
$position refer to module position, may be more than one...
$style - none, rounded, xhtml...
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.
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!