I’ve searched and searched but have not been able to find an answer to this, so thank you in advance for your help!
I am wanting to display a list (in the Admin portal, on the Products page) of all products that do NOT have a specific attribute assigned (so we can easily find products that need to be updated).
I have the same functionality already set up to display products that are missing other criteria (shipping class, weight, etc.) using a variation of this code and it works great, but I am not sure how to modify it to display products without the pa_sort-chassis attribute… so far, this is what I’ve got – it doesn’t produce any results, though.
add_action( 'admin_notices', 'products_no_chassisattribute_admin' );
function products_no_chassisattribute_admin(){
global $pagenow, $typenow;
if ( 'edit.php' === $pagenow && 'product' === $typenow ) {
echo '<div class="notice notice-warning is-dismissible"><h3>Products with NO Sort By Chassis Attribute</h3><ul>';
$args = array(
'status' => 'publish',
'visibility' => 'visible',
'limit' => -1
);
$products = wc_get_products( $args );
foreach ( $products as $product ) {
if ( ! $product = wc_get_products( array( 'pa_sort-chassis' => '' ) )) {
echo '<li><a href="' . esc_url( get_edit_post_link( $product->get_id() ) ) . '">' . $product->get_name() . '</a></li>';
}
}
echo '</ul></div>';
}
I modified the code I was already using but it does not produce any results
2
Answers
The condition
will always evaluate to true because you are assigning a value to $product instead of checking its existence.
This will cause the loop to always execute the echo statement inside the if block.
I am unsure if this will solve the issue you are having but please let me know if it does 🙂
To display products that do not have the
"pa_sort-chassis"
attribute assigned!Please try this code and it should display the products that do not have the "pa_sort-chassis" attribute assigned in the Admin portal on the Products page.
Use the
get_attributes()
method to retrieve all the attributes of a product. Then, check if the key'pa_sort-chassis'
exists in the$product_attributes
array. If it doesn’t exist, it means the product does not have the"pa_sort-chassis"
attribute assigned, and it will be displayed in the list.