Create links for custom field query - wordpress

All my post has a custom field created_by_alias, I am basically use the value in place of whereever author is used. I have customized the entry-meta function to display this value in plain text, I have also learned to build a query:
$query = new WP_Query( array('meta_key' => 'created_by_alias',
'meta_value' => 'somevalue' ));
Now for the final part: how to create a link for this piece of text, that brings a listing of all posts by this alias?
Do I need to write a template file or is there a quick way to reuse whatever code that generates links to a category, tag listing?

Not sure what you are looking for but seems to me that you want to show a link for the author posts in a specific page, if so, then you can use (using your query)
$query = new WP_Query( array('meta_key'=>'created_by_alias', 'meta_value'=>'somevalue' ));
If $query returns result and you have the id then you can use
echo get_author_posts_url( $query->posts[0]->ID ); // the `ID` from first row
Or for multiple rows, you can loop like
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
echo get_author_posts_url( get_the_ID() ) . '<br />';
}
}
Once this link is clicked, then posts will be retrieved and will be shown according to your page hierarchy, if no author template was found then finally the inedx.php will be used.
Also, if you need a custom template and want to query
$posts = get_posts(array($ID);
Now, to get the id you an use
get_user_by( $field, $value ); // 'id', 'slug', 'email', or 'login'
So, if you have the login name of the user, for example admin then you can use
$id = get_user_by( 'login', 'admin' )->ID; // php 5+
// or
$user = get_user_by( 'login', 'admin' );
$id = $user->ID;
Then get the link and echo it, whereever you want
echo get_author_posts_url( $id );

Related

Wordpress single profile page with acf gallery sharing images

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.

WORDPRESS User specific access via ID to specific contact forms CFDB7

I'm trying to implement in the code a way to show specific contact forms data to a particular user via ID but I'm having difficulty finding which part of the code to add it to.
$user_ID = get_current_user_id();
if ( $user_ID == ('2') ) {
I'm currently inside the admin-mainpage.php within the plugin files.
It's not as simple as I thought as it doesn't store the form names via db.
Any help would be appreciated.
Forms-list
It looks like Contact Forms 7 is your plugin for the forms portion while CFDB7 is an accompanying plugin that writes the form submissions to the WP database.
Get the Form ID
There are a couple ways to get the form ID. It looks like the easiest path is to look at the shortcode that the CF7 creates. You can see it in their documentation here. The code is something like [contact-form-7 id="4" title="Foo"] with id being the form ID (4 in this case).
Show the Right Form to the Right Person
Assuming you know the user ids and the related form ids you want to show them, you could write a very simple shortcode plugin to display the right forms for the right people. It'd be something like this untested code below.
//[user-form-display]
function user_form_display( $atts ){
$user_id = get_current_user_id();
if ($user_id == 2){
echo do_shortcode('[contact-form-7 id="4" title="Foo"]');
} else if ($user_id == 4){
echo do_shortcode('[contact-form-7 id="88" title="Bar"]');
}
}
add_shortcode( 'user-form-display', 'user_form_display' );
You could then put the shortcode in the regular post field and not edit either the CF7 plugin nor mess with the theme files.
You could also make the shortcode fancier and tie user ids to form ids directly in the shortcode arguments. That would take a bit more effort but is probably worth it.
Getting the Form Data
You could modify the $args to include form ids based on an association with a user id or multiple user ids. The form ids should be a field in that table. That's the example indicated below.
Alternately you could modify how the information is returned based on the same relationships by setting up the if/then statements in the $data_value lines. This is easier probably but messier in the long run.
function specfic_table_data()
{
global $wpdb;
$user_id = get_current_user_id();
if($user_id == 1){
$form_ids = array(4,6);//only returns forms with id 4 and 6 when it's user w id 1
}
$cfdb = apply_filters( 'cfdb7_database', $wpdb );
$data = array();
$table_name = $cfdb->prefix.'db7_forms';
$args = array(
'post_type'=> 'wpcf7_contact_form',
'order' => 'ASC',
'posts_per_page' => 10,
'post__in' => $form_ids,
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
$form_post_id = get_the_id();
$totalItems = $cfdb->get_var("SELECT COUNT(*) FROM $table_name WHERE form_post_id = $form_post_id");
$title = get_the_title();
$link = "<a class='row-title' href=admin.php?page=cfdb7-list.php&fid=$form_post_id>%s</a>";
$data_value['name'] = sprintf( $link, $title );
$data_value['count'] = sprintf( $link, $totalItems );
$data[] = $data_value;
endwhile;
var_dump($data);
}

WordPress - Add tags taxonomy to comments

I'm working on a project that requires comments to have tags and be searchable by tags. Is there a way to implement it in WP, or should I look for some workaround (like create child post type instead of comments and apply tags to it)?
If there is, how can I do it?
Thank you.
You can use comment meta to store and retrieve tags of a particular comment.
First of all, add the tag field to the comment form and populate the tags. The following code will add a "select" field immediately after comment textarea and populate it with the tags.
add_filter( 'comment_form_defaults', 'change_comment_form_defaults');
function change_comment_form_defaults( $default ) {
$commenter = wp_get_current_commenter();
$out = '<label for="comment_tags">Tags:</label><select name="comment_tags" multiple>';
foreach ( get_tags() as $tag ) {
$out .= '<option value="<?php echo $tag->term_id; ?>"><?php echo $tag->name; ?></option>';
}
$out .= '</select>';
$default[ 'comment_field' ] .= $out;
return $default;
}
The comment_post action is triggered immediately after a comment is stored in the database. You can use it to store post meta.
add_action('comment_post', 'add_tags_to_comment', 10, 2);
function add_tags_to_comment( $comment_ID, $comment_approved ) {
foreach($_POST["comment_tags"] as $comment_tag) {
add_comment_meta( $comment_ID, "comment_tag", $comment_tag );
}
}
Instead of storing the selected tags as an array in a single record, I prefer to store each tag as a separate record. This will make it easier to search the comments based on tags.
When you want to retrieve the tags of a comment, You can get_comment_meta
$tags = get_comment_meta($comment_ID, "comment_tag");
foreach($tags as $tag_id) {
$tag_term = get_term($tag_id, 'post_tag');
echo $tag_term->name;
}
Use WP_Comment_Query to search comments based on tags.
$tags = array(1,32,5,4); /* Replace it with tags you want to search */
$args = array(
'meta_query' => array(
array(
'key' => 'comment_tag',
'value' => $tags,
'compare' => 'IN'
)
)
);
$comment_query = new WP_Comment_Query( $args );
Hope this helped you.

Search using custom fields in wordpress

I am busy developing a web application using WordPress. I have created a custom post with a few custom fields. When I search for post using WordPress search box only post with title that match the search string get returned. I want to add custom fields on searching domain.
I there a to search by custom field values in WordPress?
following can do
$args=array(
'post_type'=>'custom post',
'order'=>'ASC',
'orderby'=>'menu_order',
'meta_query' => array (
array (
'key' => 'meta-key',
'value' => 'meta-value',
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo the_title();
}
}
wp_reset_postdata();
To query a bunch of custom fields I found it easier to use the search filters instead.
http://codex.wordpress.org/Custom_Queries Scroll down to the "Keyword Search in Plugin Table" section for an example.
Here's a quick snippet of code form my custom 'posts_where' filter so you can get an idea:
function custom_search_where($where) {
// put the custom fields into an array
$customs = array('custom_field1', 'custom_field2', 'custom_field3');
foreach($customs as $custom) {
$query .= " OR (";
$query .= "(m.meta_key = '$custom')";
$query .= " AND (m.meta_value LIKE '{$n}{$term}{$n}')";
$query .= ")";
}
$where = " AND ({$query}) AND ($wpdb->posts.post_status = 'publish') ";
return($where);
}
add_filter('posts_where', 'custom_search_where');
There's a lot more code but between the Codex example and the snippet above, it should give you a good idea.

List custom data in Wordpress

I'm developing a plugin which has its own table. I need to display the data from the table in the Wordpress frontend (for example: category page). I don't need to JOIN this table with posts table, I just need to display the data from the table, with pagination. I need a separate page/custom template from my plugin directory (talking in a context of MVC frameworks — controller), on which this data should be displayed and paginated.
Please give me an advice, what is the best practice to implement it?
Thanks.
If I understood your question then I think you need to add template_include hook to use Custom template/page from your plugin directory and you can do it like
add_filter('template_include', 'my_template', 1, 1);
function my_template($template) {
global $post;
if($post->post_content == '[myPluginPage]')
return dirname(__FILE__) . '/my_pligin_template.php';
return $template;
}
You should paste the code given above in your plugin file and also create a file in your plugin folder with name my_pligin_template.php or whatever you want but in this case in the first return statement you have to change the file name too.
Now you have to create a page in wordpress admin to show the page in the menu bar and just paste [myPluginPage] as the content. Notice if($post->post_content == '[myPluginPage]'), this will check whether it's your plugin page or not whenever you click on any menu item and if it finds the word [myPluginPage] in the content then it will return the custom template and you will be at that page.
Now you need to fetch your data from database and to do it you should write the code in this custom template file (my_pligin_template.php). To do it you can write
global $wpdb;
$pagenum = isset( $_GET['pagenum'] ) ? absint( $_GET['pagenum'] ) : 1;
$limit = 10;
$offset = ($pagenum-1) * $limit;
$total = $wpdb->get_var( "SELECT COUNT(*) FROM yourtable" );
$num_of_pages = ceil( $total / $limit );
$qry="select * from yourtable LIMIT $offset, $limit";
$result=$wpdb->get_results($qry);
if($result):
foreach($result as $row)
{
// code here
}
//Link for Pagination
$page_links = paginate_links( array(
'base' => add_query_arg( 'pagenum', '%#%' ),
'format' => '',
'prev_text' => __( '«', 'aag' ),
'next_text' => __( '»', 'aag' ),
'total' => $num_of_pages,
'current' => $pagenum
) );
if ( $page_links ) {
echo '<div class="tablenav"><div class="tablenav-pages" style="margin: 1em 0">' . $page_links . '</div></div>';
}
endif;

Resources