Show posts based on user preference in wordpress

This is an interesting snippet that will help you to set a preference for the users, so that they will choose their favorite categories and they will see posts from these categories only.


<?php
add_action( 'show_user_profile', 'extra_fields' );
add_action( 'edit_user_profile', 'extra_fields' );
add_action( 'personal_options_update', 'save_fields' );
add_action( 'edit_user_profile_update', 'save_fields' );
add_action( 'pre_get_posts', 'exclude_category' );
function extra_fields($user) {
$pref_cat = explode( ',', get_user_meta( $user->ID, 'pref_cat', true ) );
?>
<h3><?php _e("Extra profile information", "DOMAIN"); /*DOMAIN = Lang domain for l10n (optional)*/ ?></h3>
<table class="form-table">
<tbody>
<tr>
<th><?php _e("Your preferred categories", "DOMAIN"); /*DOMAIN = Lang domain for l10n (optional)*/ ?></th>
<td>
<?php
$categories = get_categories( array( 'type' => 'post' ) );
foreach( $categories as $cat ){
?>
<label><input <?php echo in_array( $cat->term_id, $pref_cat ) ? 'checked' : '' ?> type="checkbox" name="pref_cat[]" value="<?php echo $cat->term_id ?>"> <?php echo $cat->name ?></label>
<?php
}
?>
</select>
</tr>
</tbody>
</table>
<?php
}
function save_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } //Checking if the current user has ability to edit the user profile information
update_user_meta( $user_id, 'pref_cat', implode( ',', $_POST['pref_cat'] ) );
}
function exclude_category( $query ) {
if( is_user_logged_in() ) {
$current_user = wp_get_current_user();
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', get_user_meta( $current_user->ID, 'pref_cat', true ) );
}
}
}
You may also read:  Limit one blog per user in a wordpress multisite

view raw

Code.php

hosted with ❤ by GitHub

You can add those codes in your functions.php in the theme, if you think your theme won’t be changed. Otherwise mu-plugins is the best solution. To use mu-plugins, go to /wp-content/ and find the folder with name ‘mu-plugins’. If there is no folder in that name, then create a folder, name it ‘mu-plugins’, create a file inside that, give any name you like and paste the code in there. You don’t need to activate that plugin. Mu-plugins means must use plugins, so it will be activated automatically always. If you use mu-plugins then add a php start tag at the beginning of the code.

You may also read:  FAQ Plugin – The best cheap – WordPress Plugin

Enjoy! :)

You may also like

Leave a Reply