Show Post based on taxonomies choosen by the user

56 Views Asked by At

I have a website with a taxonomy called “db_themen” with different values. The posts from from my webiste are assigned to these taxonomy values from “db_themen”.

On my website, a user can choose in his frontend user profile which “db_themen” he is interested in and save this input. This works through an ACF field of the type “Taxonomy” (field name: “meine_themen”), which is linked to the taxonomy “db_themen”.

According to his input, only posts that are assigned to the same taxonomies are supposed to show on the frontend archives (Elementor archives Loop Grid) for this user.

I tried to code something within my functions.php, but I am a total beginner. The only thing this code does is hide all posts entries in the backend:

function abfrage_meine_themen($query) {
    if ($query->is_main_query() && is_user_logged_in()) {
    $ausgewaehlte_themen = get_field('meine_themen', 'user_' . get_current_user_id());
        if ($ausgewaehlte_themen) {         
            $tax_query = array(
                array(
                    'taxonomy' => 'db_themen',
                    'field'    => 'slug',
                    'terms'    => $ausgewaehlte_themen,
                ),
            );
            $query->set('tax_query', $tax_query);
        }
    }
}
add_action('pre_get_posts', 'abfrage_meine_themen');

Can someone please tell me where my mistakes are? I am sure there are several

1

There are 1 best solutions below

2
On
function abfrage_meine_themen($query) {
    // Check if this is the main query and the user is logged in
    if ($query->is_main_query() && is_user_logged_in()) {
        
        // Get the selected topics for the current user
        $ausgewaehlte_themen = get_field('meine_themen', 'user_' . get_current_user_id());
        
        // Check if topics are selected
        if ($ausgewaehlte_themen) {
            // Convert the selected topics into an array
            $ausgewaehlte_themen = explode(',', $ausgewaehlte_themen);

            // Setup the tax query
            $tax_query = array(
                array(
                    'taxonomy' => 'db_themen',
                    'field'    => 'slug',
                    'terms'    => $ausgewaehlte_themen,
                ),
            );

            // Set the tax query to the main query
            $query->set('tax_query', $tax_query);
        }
    }
}

// Hook the function into pre_get_posts
add_action('pre_get_posts', 'abfrage_meine_themen');