• is there a way to hide a specific post_type (in my case it’s WC’s ‘product’) from the search results if the user is not logged in?

    i believe Blocksy uses rest_post_search_query but i’m not sure how to add such filter…

Viewing 3 replies - 1 through 3 (of 3 total)
  • Eduard

    (@cteduard)

    Hello @maxgx

    This would indeed be possible with some additional code. I’ve generated an example for you that seems to work. Would you mind giving it a try?

    <?php
    /**
    * Hide selected CPT(s) from Blocksy search for logged-out users.
    */
    const MY_BLOCKED_SEARCH_CPTS = ['portfolio']; // change to your CPT slug(s)

    /**
    * Normal search results page query.
    */
    add_action('pre_get_posts', function ($query) {
    if (is_admin() && ! wp_doing_ajax()) {
    return;
    }

    if (! $query->is_search()) {
    return;
    }

    if (is_user_logged_in()) {
    return;
    }

    $blocked = MY_BLOCKED_SEARCH_CPTS;
    $post_type = $query->get('post_type');

    if (empty($post_type) || $post_type === 'any') {
    $post_type = get_post_types(['exclude_from_search' => false], 'names');
    } elseif (! is_array($post_type)) {
    $post_type = [$post_type];
    }

    $post_type = array_values(array_diff($post_type, $blocked));

    // Avoid empty post_type causing odd behavior.
    if (empty($post_type)) {
    $post_type = ['post'];
    }

    $query->set('post_type', $post_type);
    }, 100);

    /**
    * Blocksy live results (REST /wp/v2/search).
    */
    add_filter('rest_post_search_query', function ($args, $request) {
    if (is_user_logged_in()) {
    return $args;
    }

    // Scope to Blocksy live search requests.
    if ((string) $request->get_param('ct_live_search') !== 'true') {
    return $args;
    }

    $blocked = MY_BLOCKED_SEARCH_CPTS;
    $post_type = $args['post_type'] ?? [];

    if (empty($post_type) || $post_type === 'any') {
    $post_type = get_post_types(
    ['public' => true, 'show_in_rest' => true],
    'names'
    );
    unset($post_type['attachment']);
    } elseif (! is_array($post_type)) {
    $post_type = [$post_type];
    }

    $args['post_type'] = array_values(array_diff($post_type, $blocked));

    if (empty($args['post_type'])) {
    $args['post_type'] = ['post'];
    }

    return $args;
    }, 1000, 2);

    Let me know if this works for you.

    Thanks,
    Eduard

    Thread Starter maxgx

    (@maxgx)

    hi @cteduard ,

    had to fiddle with the code a bit, as for whatever reason it kept ignoring the setting of a const outside the two add_action()s, but adding the value as a variable did the trick!

    so smart it also hides results from the autosuggest…

    perfect, thanks a lot!

    Eduard

    (@cteduard)

    Thank you for the confirmation, @maxgx!

Viewing 3 replies - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.