0

I would like to replace the permalink for all products in a woocommerce/wp installation with a custom link, if it set in a custom_post_meta.

The custom_post_meta is setup and working fine. From all I have read, the function below should do the trick:

function eli_changeProductLink($permalink, $post) {
    if ('product' == $post->post_type) {
        $custom_url = get_post_meta($post->id, '_eli_product_link', true);
        $permalink  = $custom_url ?: $permalink;
    }

    return $permalink;
}

add_filter('post_type_link', 'eli_changeProductLink', 11, 2);

I'm giving it priority 11 because I want it run after wc_product_post_type_link(), which has a priority of 10.

Can anyone spot what am I missing here? Or come up with possible causes why this might not work as expected? Using WC 2.4.10 with WP 4.3.1 (both latest at the time of posting).

Thank you.

2
  • @toscho: should I delete this or do you think it could be helpful for others?
    – tao
    Nov 25, 2015 at 0:32
  • Honestly, I am not sure. On the one hand, it is just a typo. On the other hand, there is something others can learn from in your problem. I'll write an answer, and then we leave it up to the community whether we keep or drop it.
    – fuxia
    Nov 25, 2015 at 1:10

2 Answers 2

1

The $post in your callback handler is an object, and object properties, like variables, are case sensitive. So you have to use $post->ID, not $post->id.

The question here is: How can we prevent errors like this one during development?

For objects, there is a simple solution: use type hinting and an IDE that makes use of it.

If you change the signature of your callback handler to this …

function eli_changeProductLink($permalink, \WP_Post $post)

… an IDE like PHPStorm or Eclipse will suggest the correct property names while you are typing:

IDE screenshot

The second lesson we can take from this: Use a consistent naming scheme for your own variables and properties, unlike WordPress which is mixing uppercase and lowercase, underscore and hyphens in names. Sticking to just one scheme will make the life of others easier when they have to work with your code.

1
  • I learned Yii2 by abusing type-hinting (among other things). I have no idea why I never used it in WP so far. For this particular project it would have been useles anyway, as my involvement was so small that it didn't make sense to pull all of it on my local machine. So the IDE had no idea it's a WP. But I really appreciate the eye opener.
    – tao
    Nov 25, 2015 at 1:46
0

Silly me. Haven't used WP in a while and completely forgot ID should be capitalized.

Changed post->id to post->ID and it's working as intended.

Sorry for wasting your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.