Wordpress single profile page with acf gallery sharing images - wordpress

Good afternoon devs, I develop a project that consists of users profiles with a record created with fields from the ACF, including the image gallery field, my problem is ... as I only use one page to display this profile, the image gallery is makes it shared even with the option of "attached to the post", as I only use one page for this, example "/profile?userid=userid".
Is there any other good practice for doing this?
I would like suggestions.
one part profile edit
function acf_profile_edit( $atts ) {
$a = shortcode_atts( array(
'field_group' => ''
), $atts );
$uid = get_current_user_id();
if ( ! empty ( $a['field_group'] ) && ! empty ( $uid ) ) {
$options = array(
'post_id' => 'user_'.$uid,
'field_groups' => array( intval( $a['field_group'] ) ),
'return' => add_query_arg( 'updated', 'true', get_permalink() )
);
ob_start();
acf_form( $options );
$form = ob_get_contents();
ob_end_clean();
}
return $form;
}
add_shortcode( 'profile_edit', 'acf_profile_edit' );
Edit...
This code resolved my problem
add_filter('ajax_query_attachments_args', 'restrict_images_to_user');
function restrict_images_to_user($query) {
$gallery_images = 'field_5e4d799b34145';
$gallery_videos = 'field_5e5597e37f2c7';
if ( isset($_POST['query']['_acfuploader'] )
&& ( isset($_POST['query']['_acfuploader']) == $gallery_images || isset($_POST['query']['_acfuploader']) == $gallery_videos ) ) {
$author = get_current_user_id();
$query['author'] = $author;
}
return $query;
}

If you are using one page, use a page template called page-profile.php, the bit after page- must match the name of the page you have assigned.
Then use the WordPress Post Loop:
if (have_posts()) :
while (have_posts()) :
the_post();
the_content();
endwhile;
endif;
You can assign a username to the posts and the posts loop will only return the stuff associate with that username.
Another way would be to get the current username, then can you make an extra acf field with the username in and then do a check.
This is an example and will be exactly correct, but may be able to help you with suggestions.
If(content && username == currentuser)
{
$content = acf content;
}
then later in your page you can echo the content where you need it and will only be the content for the current username, or you can also do it with the user id.

Related

how to change edit url with "Id" to edit url with "Slug" in Wordpress

I have this is WordPress Post editing Url:
https://example.com/wp-admin/post.php?post=ID&action=edit
and I want to change it to Slug Not the ID Like This:
https://example.com/wp-admin/post.php?post=Slug&action=edit
I was trying to edit the post with this Url but is not working:
https://example.com/wp-admin/post.php?post=MyPostSlug&action=edit
In order to change the edit post link structure, you can use the get_edit_post_link filter like so:
add_filter( 'get_edit_post_link', 'so_73914075_get_edit_post_link', 10, 3);
function so_73914075_get_edit_post_link($link, $post_id, $context) {
$post = get_post( $post_id );
if ( ! in_array( $post->post_type, array( 'post', 'page' ) ) ) {
return $link;
}
$post_type_object = get_post_type_object( $post->post_type );
if ( 'revision' === $post->post_type ) {
$action = '';
} elseif ( 'display' === $context ) {
$action = '&action=edit';
} else {
$action = '&action=edit';
}
if ( 'display' === $context ) {
$post_type = '&post-type=' . $post->post_type;
} else {
$post_type = '&post-type=' . $post->post_type;
}
$custom_edit_link = str_replace( '?post=%d', '?post-name=%s', $post_type_object->_edit_link );
return admin_url( sprintf( $custom_edit_link . $action . $post_type, $post->post_name ) );
}
This will change the edit links for regular posts and pages to something like this:
https://example.com/wp-admin/post.php?post-name=the-post-slug&action=edit&post-type=post
WARNING: make sure you limit this to only the post types you need to change the URL for. Making this change global will almost surely
have unintended effects over other plugins
However, making the admin panel actually load the edit screen is not that easy.
Looking at the source code of the wp-admin/post.php file, you will see that there is no way to hook into the flow and populate the $post_id variable with the post id matching the slug you are sending through.
That means you have 2 options:
RECOMMENDED Update the edit link to whatever format you want and then create an admin redirect function that pulls the slug from the initial URL and redirects to the actual edit page with the ?post=%d in it.
NOT RECOMMENDED Create a new admin edit page that will understand your URL structure and include the wp-admin/post.php after the code that pulls the $post_id based on the slug.
The 2nd method might come with lots of extra code you need to write to cover all the cases and all the instances a post reaches the post.php in the admin panel

How to display a custom post type feed in the sidebar of a category page?

I have a custom post type setup and in the sidebar of every page on the site it is set to display a random post from that custom post type (named "reviews").
This works great everywhere except for category pages for the normal / standard / default post type of "post" where even though the query is setup to only use the custom post type "reviews" it only pulls from the default blog posts.
Is there something I am leaving out to make sure this works even on category pages?
Here is the code I am using that works fine on non category pages, you can see it is restricted to just the "reviews" post type:
// the query
$review_query = new WP_Query( array (
'post_type' => 'reviews', // Display just this post type
'orderby' => 'rand',
'posts_per_page' => 1,
)
);
You can create shortcode that you can put in any widget area you want.
Something like:
function wpb_rand_posts() {
if ( $the_query->have_posts() ) {
$string .= '<ul>';
while ( $the_query->have_posts() ) {
//do stuff
}
$string .= '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
$string .= 'no posts found';
}
return $string;
}
add_shortcode('wpb-random-posts','wpb_rand_posts');
add_filter('widget_text', 'do_shortcode');
Ok so it turns out the code I had added to functions.php to make sure a different custom post type was displaying in the category feed was interfering.
So this was the original code snip I used to do that:
// Show notable cases in tag archives
function themeprefix_show_cpt_archives( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'nav_menu_item', 'post', 'cases'
));
return $query;
}
}
And I changed that to this:
// Show notable cases in tag archives
function themeprefix_show_cpt_archives( $query ) {
if( empty( $query->query_vars['suppress_filters'] ) && ( is_category() || is_tag() ) ) {
$query->set( 'post_type', array(
'nav_menu_item', 'post', 'cases'
));
return $query;
}
}
And added suppress_filters' => true to my query, and this resolved my issue. If anyone else runs into this see what else in your theme may be modifying the query at a higher level through a function like this or plugin as this is a solution specific to the code in my theme.

how to determine if current user is admin in wordpress gutenberg UI

I have found .canUser() method. But it returns undefined for me.
I'm calling it in UI with:
wp.data.select( 'core' ).canUser('create', 'users')
Where am I wrong?
Here are the docs for reference:
enter link description here
Is there any known plausible way to do it in JS UI plugin code itself? Or how did you do it maybe?
You need to use useSelect in order to achieve this:
wp.data.useSelect( (select) => select( 'core' ).canUser( 'create', 'users' ) );
After Analyzing Gutenberg source for a bit found out I was semi right.
The way to check this is around users (only admin can do that).
Here is how one could do it in Gutenberg UI Block code.
wp.data.select( 'core' ).canUser( 'create', 'users' )
THe only problem it did not work while the breakpoint was set.
You can use current_user_can() to check the user roles.
https://developer.wordpress.org/reference/functions/current_user_can/
function current_user_can( $capability ) {
$current_user = wp_get_current_user();
if ( empty( $current_user ) ) {
return false;
}
$args = array_slice( func_get_args(), 1 );
$args = array_merge( array( $capability ), $args );
return call_user_func_array( array( $current_user, 'has_cap' ), $args );
}
To check if the user is editor or administrator:
<?php if( current_user_can('editor') || current_user_can('administrator') ) { ?>
// Stuff here for administrators or editors
<?php } ?>

Using WP_Query() to check if a post exists by slug

I am writing a 404.php for wordpress. I have the plugin 'rolescoper' installed, and some pages require the user be logged in to view. Rolescoper doesn't offer any way to distinguish between a page not found (404) and a permission denied (403).
I've been able to build this functionality into my pages using the following code:
$the_query = new WP_Query ( 'pagename=' . $_SERVER['REQUEST_URI'] );
$is_valid_page = ! empty ( $the_query -> queried_object -> post_title );
But, surprisingly, the same method does does not work for posts:
$args = array (
'post_type' => 'post',
'name' => str_replace ( "/", "", $_SERVER['REQUEST_URI'] )
);
$the_post_query = new WP_Query ( $args );
$is_valid_post = ! empty ( $the_post_query -> queried_object -> post_title );
When I do a var_dump on $the_post_query i get something that shows 0 results found. I am sure that the page I'm checking for exists.
Any idea how to use wp_query() to query for a post by slug?
Thanks!
After digging through the docs, I found that Rolescoper provided a nice function, is_restricted_rs(), for solving this problem:
//get the slug requested
$slug = $_SERVER [ 'REQUEST_URI' ];
//First check if it's a page and restricted
$page_id = get_page_by_path ( $slug )->ID;
$page_restricted = is_restricted_rs ( $page_id );
//Then check if it's a post and restricted
$args = array(
'name' => $slug,
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
if ( $my_posts ) {
$post_id = $my_posts[0]->ID;
}
$post_restricted = is_restricted_rs ( $post_id );
//then set $content_restricted for use below
$content_restricted = $post_restricted || $page_restricted;
The rolescoper plugin has become defunct and we developed a solution which does not require any external plugin. Instead, we added some code to our theme and added a custom field to each page that we wanted to restrict access to.
This isn't as robust as rolescoper was, but for our use case it was perfect. We have only a few user classes and so I just hardcode the different classes and that's enough for us. I'm sure a similar solution could be used for more complex cases, especially if you expanded on the custom UI code.
I happened to name the field "dhamma_perms" but you could name it anything you want:
function is_restricted() {
return item_restricted(get_post(), wp_get_current_user());
}
function item_restricted($page, $user) {
$dhamma_perms = get_post_meta($page->ID, "dhamma_perms", true);
$requires_os = $dhamma_perms == "oldstudents";
$requires_worker = $dhamma_perms == "workers";
if (!is_user_logged_in()) {
return $requires_os || $requires_worker;
} else if (get_userdata($user->ID)->user_login == "oldstudent") {
return $requires_worker;
} else {
//dhammaworkers and all named users have full read access
return false;
}
}
I then modified any page which could be restricted to have code like this at the top:
<?php get_header(); ?>
<?php if (is_restricted()) : ?>
<?php show_404(); ?> //I just pasted the full content of our 404 page into a function. The 404 page shows a faux-403 page (WP doesn't have real 403 pages) if the content exists but is restricted.
<?php else: ?>
//show normal page stuff
I also modified the header.php to have a proper title for 404 and 403 pages:
<?php if (is_restricted()) : ?>
<title> <?php echo "Login Required " . get_theme_mod('dhamma_title_separator') . " " . get_bloginfo('name'); ?></title>
<?php else: ?>
<title><?php wp_title( get_theme_mod('dhamma_title_separator'), true, "right" ); bloginfo('name'); ?></title>
<? endif; ?>
Finally, I added a custom UI to posts and pages so it's easy to select permissions:
//Register the permissions metabox for posts and pages
function add_perms_box( $post ) {
$screens = [ 'post', 'page', 'wporg_cpt' ];
foreach ( $screens as $screen ) {
add_meta_box(
'dhamma_perms_box', // Unique ID
'Permissions', // Box title
'perms_box_html', // Content callback, must be of type callable
$screens // Post type
);
}
}
function perms_box_html() {
$value = get_post_meta(get_the_ID(), "dhamma_perms", true);
?>
<select name="dhamma_perms" id="dhamma_perms" class="postbox">
<option value="public" <?php selected($value, 'public');?>>Public</option>
<option value="oldstudents" <?php selected($value, 'oldstudents');?>>Old Students Only</option>
<option value="workers" <?php selected($value, 'workers');?>>Dhamma Workers Only</option>
</select>
<?php
}
add_action('add_meta_boxes', 'add_perms_box');
function dhamma_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
// Exits script depending on save status
if ( $is_autosave || $is_revision ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'dhamma_perms' ] ) ) {
update_post_meta( $post_id, 'dhamma_perms', $_POST[ 'dhamma_perms' ] );
}
}
add_action( 'save_post', 'dhamma_meta_save' );
This created a new dropdown on each page and post for us:
I hope this is helpful for anyone else trying to get some simple permissions on a wordpress site!

get_avatar alternative for Buddypress's uploaded photo

I am using the following snippet in my theme to get the logged-in user's avatar of the default wp user's setting page.
<?php echo get_avatar($id_or_email, $size='64', $default, $alt='User name' ); ?>
However, After installing the buddypress; I wanted to display the uploaded profile's photo of the user where the above snippet only shows the default wp avatar.
Any idea on how to achieve that?
You should enable both options:
<?php
if ( empty ( bp_loggedin_user_id() == false ) ) {
$user_id = bp_loggedin_user_id();
echo bp_core_fetch_avatar( array( 'item_id' => $user_id) );
} else {
echo get_avatar($id_or_email, $size='64', $default, $alt='User name' );
}
?>
Use the BuddyPress function bp_core_fetch_avatar
$user_id = bp_loggedin_user_id();
echo bp_core_fetch_avatar( array( 'item_id' => $user_id) );
Review the function in bp-core/bp-core-avatars.php to see the available arguments.

Resources