Skip to content
Advertisement

How to pass parameters to add_feed in an OOP singleton

I struggle creating separate page feeds (list of URLs) in each language when WPML is active.

The plan is to have different feed names for each language, such as feed_name_en or feed_name_fr.

I wrote the following function that iterates through each available language on the site and should output a feed for each language containing only the pages in the particular language.

I found other examples that show how to pass parameters within add_action using closures. (eg. add_action('init', function() use($param) { some_out_of_scope_function($param) } )

But in my function I am getting the following error:

Object of class Closure could not be converted to string in

I have the suspicion that it is because I am using OOP to encapsule the function in an array add_feed( $feedname, array( $this, ... ) ). But I have no idea how to work around this.

How shall I approach this?

JavaScript

Advertisement

Answer

If you’re using PHP 5.4 or newer, you can just pass the closure with the $lang parameter to the add_feed() function and $this will retain the reference to the object:

JavaScript

Note that your create_page_feed() method needs to be public so WordPress can access it:

JavaScript

(see What is the difference between public, private, and protected? for more details.)

Here’s a tested & working demo plugin that registers a feed using the Singleton pattern:

JavaScript

The feed will be available here: https://www.example.com/feed/some_rrs_feed.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement