Cannot read product images on list page in Magento2 - gallery

I'm trying to load product images on list page. Here is my code:
$_productCollection = $block->getLoadedProductCollection();
foreach ($_productCollection as $_product){
$images = $product->getMediaGalleryImages();
The $_product variable is fine. The variable $images is always null.

I was able to solve this with following code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_productCollection = $block->getLoadedProductCollection();
foreach ($_productCollection as $_product){
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($id);
$images = $product->getMediaGalleryImages();
}

You need to use the addMediaGalleryData method.
See this answer on magento.stackexchange.com for more details.

Related

How to determine the active WooCommerce Product Variation Image URL

I am trying to pass the active product variation to a wordpress widget.
The widget code for displaying the image is currently:
$product = wc_get_product(get_the_ID());
$artwork_url = wp_get_attachment_url($product->get_image_id());
$unit = get_option('woocommerce_dimension_unit');
$height2 = $product->get_height();
$width2 = $product->get_width();
$height = $height2;
$title = get_the_title();
$price = $product->get_price();
$measurements_display = $widget->dimensions == 1 ? 'WxH' : 'HxW';
The $artwork_url is what I am having problems with. When I visit the site, the variation options successfully display the appropriate variation image. I would like to pass that value onto the widget with the $artwork_url expression. I've tried pulling thumbnails, feature images, wo-post-images, and am not getting anywhere.
If anyone could offer a suggestion to this, i'd greatly appreciate any advice.
Thanks
Cameron
I've tried defining $variations and $post-image, $variable_product, but can't seem to get the language right.
To get the active variation image URL in the widget, you can try the following code:
$product = wc_get_product(get_the_ID());
$variation_id = isset($_REQUEST['variation_id']) ? $_REQUEST['variation_id'] : '';
if ($variation_id) {
$variation = new WC_Product_Variation($variation_id);
$artwork_url = wp_get_attachment_url($variation->get_image_id());
} else {
$artwork_url = wp_get_attachment_url($product->get_image_id());
}
$unit = get_option('woocommerce_dimension_unit');
$height2 = $product->get_height();
$width2 = $product->get_width();
$height = $height2;
$title = get_the_title();
$price = $product->get_price();
$measurements_display = $widget->dimensions == 1 ? 'WxH' : 'HxW';
This code first checks if a variation_id is present in the request parameters. If it is, it creates a new WC_Product_Variation object with that ID and gets the variation's image URL. If not, it gets the parent product's image URL as before.

ACF: data not retrieved correctly in the_loop() IF user is not the post author

i have a loop which retrieves correctly post data, (title, etc) and works fine with ACF fields ONLY if the viewer is the post author, it is not working IF the viewer is someone else... :(
public static function getFields() {
$postID = get_the_ID();
$fields = [];
$array_anagrafica = [];
if( have_rows('anagrafica', $postID) ) { // <<- it's not working even with no $postID
while (have_rows('anagrafica', $postID)) {
the_row();
$array_anagrafica['cf'] = get_sub_field('codice_fiscale');
$array_anagrafica['piva'] = get_sub_field('partita_iva');
any hint?
it is a matter of acf_form -> using acf_form() toghether with acf_form_head() replicates backend form and can then be properly initated.

Wordpress custom author urls

I want to implement custom author urls.
Currently the author urls are like this:
http://site.com/author/author-name/
I want to do something like
http://site.com/my-custom-url-here
For each individual user.
I have tried using author_rewrite_rules filter, using the following code, this converts the url correctly but this gives me a page not found message when i browse the url
add_filter('author_link', 'no_author_base', 1000, 3);
function no_author_base($link, $author_id) {
$link_base = trailingslashit(get_option('home'));
$link = preg_replace("|^{$link_base}author/|", '', $link);
return $link_base . $link;
}
add_filter('author_rewrite_rules', 'no_author_base_rewrite_rules');
function no_author_base_rewrite_rules($author_rewrite) {
global $wpdb;
$author_rewrite = array();
$authors = $wpdb->get_results("SELECT user_nicename AS nicename from $wpdb->users");
foreach($authors as $author) {
$author_rewrite["({$author->nicename})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]';
$author_rewrite["({$author->nicename})/?$"] = 'index.php?author_name=$matches[1]';
}
return $author_rewrite;
}
Any help would be greatly appreciated!
Thanks.
UPDATE
Problem is solved!, basically i did not know about calling the flush_rewrite_rules function.
Solved!
Here's how i did it:
i did not need the author_link filter so i removed it, my custom urls are stored in usermeta table so i fetched them and passed them into the rewrite array, and most importantly I DID NOT KNOW ABOUT FLUSHING THE REWRITE CACHE AND THAT WAS THE REASON MY ORIGINAL CODE WAS NOT WORKING
Heres the full code:
add_filter('author_rewrite_rules', 'my_author_url_with_custom_url_rewrite_rules');
function my_author_url_with_custom_url_rewrite_rules($author_rewrite) {
global $wpdb;
$author_rewrite = array();
$authors = $wpdb->get_results("SELECT ID, user_nicename AS nicename, meta_value as profile_name
from $wpdb->users
LEFT JOIN wp_usermeta ON wp_usermeta.user_id = $wpdb->users.ID
WHERE meta_key = 'profile_name'");
foreach ($authors as $author) {
$author_rewrite["{$author->profile_name}/page/?([0-9]+)/?$"] = 'index.php?author_name=' . $author->nicename . '&paged=$matches[1]';
$author_rewrite["{$author->profile_name}/?$"] = "index.php?author_name={$author->nicename}";
}
return $author_rewrite;
}
flush_rewrite_rules(false);
dont forget to comment the flush_rewrite_rules call after you are done with rewrite rules, it is very expensive!
try this one. for get your author url.
<?php the_author_posts_link(); ?>
if post a admin or a author and want to show his/her all post in one page. so, you need to get his/her url automatic. then try this one

Wordpress shortcode only returning 1 from feed despite using foreach

I am trying to create a custom Wordpress plugin which utilises shortcodes to output what I want. In this text code I am attempting to read an rss file and spit out just a list of the top 5 feeds.
The $showno is one of the shortcode variables so I can use the following [player show=foo snowno=5]. In the example code $show isn't used.
The code below only shows the most recent item in the feed list. If I change the return to echo then it works as expected except it show at the top of the post instead of where I've entered the shortcode. I searched for an answer to this and the solution offered was simply "use return" which I've done...
Appreciate advice. Thanks
include_once(ABSPATH . WPINC . '/rss.php');
$num_items = $showno;
$feedurl = 'http://feeds.bbci.co.uk/news/rss.xml';
$feed = fetch_rss($feedurl);
$items = array_slice ($feed->items, 0, $num_items);
foreach ($items as $item ) {
$title = $item[title];
$mp3link = $item[link];
$description = $item[description];
return "<li>$title - $description</li>";
}
Shortcodes should be returned not echoed.
In your code, you are breaking the execution of the foreach and returning the first value.
You should build a string variable and after the foreach loop return it, so all your loop will be included, e.g.:
$final_html = '';
foreach( $items as $item )
{
$final_html .= "<li>$title - $description</li>";
}
return $final_html;

How do I get product category information using collections in Magento

I am trying to output all the products from our Magento shop - the following code works, however I also need to grab the category id & the parent category name too. Can anyone suggest how I can do this?
$product = Mage::getModel('catalog/product');
$productCollection = $product->getCollection()
->addAttributeToSelect('*');
foreach ( $productCollection as $_product ) {
echo $_product->getName().'<br/>';
}
In some instances $_product->getCategory() can return empty and cause an error.
A better solution is to fetch categories by ID:
$categoryIds = $_product->getCategoryIds();
foreach($categoryIds as $categoryId) {
$category = Mage::getModel('catalog/category')->load($categoryId);
echo $category->getName();
echo $category->getUrlPath();
}
Since products can be assigned to multiple categories, I think your concept may be a bit off unless you are loading a collection for each category. What do you anticipate seeing if there are multiple categories for a given product?
Regardless, from within a category page, you can use the following:
$currentCat = $_product->getCategory();
To get all categories to which this product belongs:
$categories = $_product->getCategoryCollection();
foreach($categories as $_category) {
// do something
}
Hope that helps. Thanks,
Joe

Resources