Hi @araislamara!
I can see some mistakes in your code:
- You don’t attach, but fire an action. Use
add_action
, not do_action
- You are trying to attach to hook from within REST API callback, but this way, you try to hook into action after it has been executed. It isn’t possible in WordPress, as you should attach all your hook callbacks before a hook will be dispatched (i.e. with
do_action
)
To do this correctly, you should first hook into Flexible Wishlist, and from within, register a REST API route. It is important to preserve a correct order of execution.
Here’s an example:
function get_wishlist_products_by_user( $wishlist_repository, $user_id ) {
/** @var array $wishlist One user can have multiple wishlists */
$wishlists = $wishlist_repository->get_by_user( $user_id );
$product_id = [];
foreach ( $wishlists as $wishlist ) {
$wishlist_items = $wishlist->get_items();
foreach ( $wishlist_items as $wishlist_item ) {
$product_id[] = $wishlist_item->get_product_id();
}
}
return $product_id;
}
// Hook into Flexible Wishlist initiation point
add_action(
'flexible_wishlist/init',
// Here we can access WishlistRepository, which we will need to get products for user
function ( $_, $wishlist_repository ) {
// Register our REST API route
add_action(
'rest_api_init',
// This may be done better with OOP and keeping wishlist repository as class field
// Otherwise, we need to pass it down as closure argument
function () use ( $wishlist_repository ) {
register_rest_route(
'my_flexible_test',
'/v1',
[
'methods' => 'GET',
'callback' => static function () use( $wishlist_repository ) {
return rest_ensure_response(
get_wishlist_products_by_user( $wishlist_repository, 1 )
);
},
'permission_callback' => '__return_true'
]
);
}
);
},
10,
2
);