Using the Recipe Object for front-end changes

As of version 9.5.0 there is an easy way to dynamically alter the recipe in the front-end through the recipe object. This can be used to create your own adjustable servings UI, for example.

Accessing the Recipe

Using JavaScript, you have the WPRecipeMaker.manager object available. It can be used to find all recipes on the page, for example:

const recipeIds = window.WPRecipeMaker.manager.findRecipesOnPage();

This gives you an array of recipe IDs found on the page, which could then be used to get the full recipe object.

window.WPRecipeMaker.manager.getRecipe( 6 ).then( (recipe) => {
  if ( recipe ) {
    // Do something with the recipe.
} );

The getRecipe() function returns a Promise, allowing you to retrieve the data for any recipe (whether it was already shown on the page or not). Alternatively getRecipeImmediately() is available as well, but will only be able to return the recipe object if it had already been loaded (for example in a single post containing that recipe card).

Using the Recipe Object

Once you have the recipe object, the fun can start. When building a custom UI for adjustable servings, you can easily set the servings and see the changes happen without worrying about handling that part yourself:

window.WPRecipeMaker.manager.getRecipe( 41 ).then( (recipe) => {
  if ( recipe ) {

Similarly, setUnitSystem() is available to change the unit system (1 is the default system, 2 the converted one).

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.