Search using custom fields in wordpress - 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.

Related

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.

Wordpress get post id with matched post content

Is there a way in Wordpress so that I would generate a sub-string of a post content and it would give me the post id?
Thanks in advance.
It can be achieved using awesome WP Query Class of WordPress with search parameter. e.g. Following query will search for any posts with "hello" words in it and display its Post Ids as you needed:
<?php
// 's' parameter is for search
$the_query = new WP_Query( array( 's' => 'hello' ) );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
//now we can echo anything we want like e.g. IDs
echo get_the_ID();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>

Getting Only Custom Post Types Posts with WP_Query

I am trying to get custom posts with WP_Query but it's not returning only custom post type posts but also default posts too.
I am using
$args = array (
'post_type' => array ('survey')
);
$sPosts = new WP_Query($args);
as a result I am getting 'survey' posts as well as default posts, I only need it to return 'survey' posts.
P.S. when I use query_posts() it returns the required result, but just not getting it done with WP_Query and I prefer to use WP_Query not the query_posts()
Please try it like that....
<?php
$new = new WP_Query('post_type=discography');
while ($new->have_posts()) : $new->the_post();
the_content();
endwhile;
?>
I believe this custom query should actually be your main query, in which case you should not use a custom query
The problem you are facing is either due to
Wrong use somewhere of pre_get_posts. Remember, pre_get_posts alters all instances of WP_Query, backend and front end. Lack of correct use will break all queries
You have not changed the loop to be objects of your new query
To come back to the point, as said, this is suppose to be the main query, so lets target that problem.
The first thing to do would be to delete the custom query. Once you have done this, you would only see normal post.
We are now going to use pre_get_posts to alter the main query to only show custom posts. Paste the following inside your functions.php
add_action( 'pre_get_posts', function ( $q ) {
if( !is_admin() && $q->is_main_query() && $q->is_home() ) {
$q->set( 'post_type', 'YOUR CPT' );
}
});
You should now just see post from your cpt on the homepage
EDIT
Your index.php should look something like this
if( have_posts() ) {
while( have_posts() ) {
the_post();
// HTML mark up and template tags like the_title()
}
}else{
echo 'No posts found';
}
This code can get all the posts in a custom post type..,
wp_query is the function can get all the posts in the custom post type. wp_query requires array, so you can give the custom post type name in post id to array
$args = array(
'post_type' => 'address', //custom post type
'posts_per_page' => -1 // get all posts
);
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();
echo( get_the_title() );
}
}

Create links for custom field query

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 );

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