0

I'm a complete newbie to php, and I'm trying to use a function suggested by FacetWP to pre-select the post results shown to users. (I'm using this method, rather than pre_get_posts as I want users to be able to add additional categories back in to the results, if their pre-selected values don't meet their needs.)

I have successfuly tested a version of the function below where I was calling and using a different meta key, which has a basic value stored, but for this meta key, the data is serialized. Not being familiar with php, my attempts to unserialise have resulted in a lot of white screens...

Function

add_filter( 'facetwp_preload_url_vars', function( $url_vars ) {
    $topics_of_interest = get_user_meta(get_current_user_id(),'topics_of_interest',true);
     if ( 'reading' == FWP()->helper->get_uri() ) ;
    {
        if ( empty( $url_vars['categories'] ) ) {
            $url_vars['categories'] = $topics_of_interest;
        }
    return $url_vars;
}
}
           );

When I query this meta key for my user ID in the DB, I get back:

a:4:{i:0;s:8:"Business";i:1;s:28:"Current affairs and politics";i:2;s:28:"DIY, crafts and housekeeping";i:3;s:5:"Music";}

The function needs it to be quoted thus (manually entering the values thus works):

['Business','Current affairs and politics','etc','etc']

I have tried $topics_of_interest = unserialize () {get_user_meta(get_current_user_id(),'topics_of_interest',true);} but that errors.

Is this a syntax problem or is there a simpler / better / safer method?

EDIT Apparently serialising / unserialising the data isn't the issue here.

The function will take manually entered values:

['Business','Current affairs and politics','etc','etc']

and produce a result akin to a manually selecting a URL query string:

?_categories=business%2Ccurrent-affairs-and-politics%2Cdiy-crafts-housekeeping%2Cmusic

So the question is why it is not doing so from the code above, if get_user_meta automatically unserialises the data it fetches?

8
  • It should be unserialised when you use get_user_meta(). How are you saving the field? – Jacob Peattie Apr 17 at 12:04
  • I've included in the question what I get when I query that field. Is that serialised data, or am I mistaken? – smallnorthumbrianvillage Apr 17 at 13:41
  • It is. Which means something is wrong. Is that what you get when you query the database directly? Or when you use get_user_meta()? – Jacob Peattie Apr 17 at 13:45
  • When I query the db directly. So is it an error in my code? – smallnorthumbrianvillage Apr 17 at 14:28
  • get_user_meta() unserializes the value. Did you not try it without manually unserializing? – Jacob Peattie Apr 17 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.