My if ( $filter == 'on' ) in the ugrestriction_filter function seems to not be working in this code when viewing a post. I'm executing this from functions.php It does work when viewing a page. How can I make this work?
Here's my code:
// Join metadata
function ugrestriction_join($join) {
global $wp_query, $wpdb;
$join .= "LEFT JOIN ($wpdb->postmeta) ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
return $join;
}
add_filter('posts_join', 'ugrestriction_join');
// Prevent duplicates
function ugrestriction_distinct( $where ) {
global $wpdb;
return "DISTINCT";
return $where;
}
add_filter( 'posts_distinct', 'ugrestriction_distinct' );
// Filter posts
function ugrestriction_filter( $where, $wp_query )
{
global $wpdb, $post, $current_user, $wp_query;
get_currentuserinfo();
$user_id = $current_user->ID;
$page_id = $wp_query->get_queried_object_id();
$post_id = $post->ID;
$meta_key1 = '_ugrestriction';
$meta_key1_value = 'on';
$postids=$wpdb->get_col( $wpdb->prepare(
"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = 'on'", "_ugrestriction"
) );
//$postids = array("70", "1", "2", "3");
if (in_array($post_id, $postids)) {
$filter = 'on';
} elseif (in_array($page_id, $postids)) {
$filter = 'on';
}
if ( $filter == 'on') {
$where .= " AND ($wpdb->postmeta.meta_key = '_ugrestriction' AND $wpdb->postmeta.meta_value = 'on' AND " . $wpdb->posts . " .post_author =". $user_id .")";
}
return $where;
}
add_filter( 'posts_where', 'ugrestriction_filter', 10, 2 );
From the documentation:
Certain functions which retrieve posts do not run filters, so the
posts_where filter functions you attach will not modify the query. To
overcome this, set suppress_filters to false in the argument array
passed to the function
Source
Have you tried this?
Related
I'm getting the following error in my wordpress dashboard which correlates to a piece of code i've written, however I'm not sure how to fix the error:
Notice: Undefined index: draft in /home/sites/samskirrow.com/public_html/skizzar-test/wp-content/mu-plugins/skizzar-dashboard.php on line 331
Here is the code it's referring to:
/******************************************************************
/* REMOVE BRACKETS AROUND PAGE COUNTS
/******************************************************************/
foreach( array( 'edit-post', 'edit-page', 'edit-movie', 'upload' ) as $hook )
add_filter( "views_$hook" , 'wpse_30331_custom_view_count', 10, 1);
function wpse_30331_custom_view_count( $views )
{
global $current_screen;
switch( $current_screen->id )
{
case 'edit-post':
$views = wpse_30331_manipulate_views( 'post', $views );
break;
case 'edit-page':
$views = wpse_30331_manipulate_views( 'page', $views );
break;
case 'edit-movie':
$views = wpse_30331_manipulate_views( 'movie', $views );
break;
case 'upload':
$views = wpse_30331_manipulate_views( 'attachment', $views );
break;
}
return $views;
}
function wpse_30331_manipulate_views( $what, $views )
{
global $user_ID, $wpdb;
/*
* This is not working for me, 'artist' and 'administrator' are passing this condition (?)
*/
if ( !current_user_can('artist') )
return $views;
/*
* This needs refining, and maybe a better method
* e.g. Attachments have completely different counts
*/
$total = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE (post_status = 'publish' OR post_status = 'draft' OR post_status = 'pending') AND (post_author = '$user_ID' AND post_type = '$what' ) ");
$publish = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_author = '$user_ID' AND post_type = '$what' ");
$draft = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = '$user_ID' AND post_type = '$what' ");
$pending = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'pending' AND post_author = '$user_ID' AND post_type = '$what' ");
$trash = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'trash' AND post_author = '$user_ID' AND post_type = '$what' ");
/*
* Only tested with Posts/Pages
* - there are moments where Draft and Pending shouldn't return any value
*/
$views['all'] = preg_replace( '/\(.+\)/U', ''.$total.'', $views['all'] );
$views['publish'] = preg_replace( '/\(.+\)/U', ''.$publish.'', $views['publish'] );
$views['draft'] = preg_replace( '/\(.+\)/U', ''.$draft.'', $views['draft'] );
$views['pending'] = preg_replace( '/\(.+\)/U', ''.$pending.'', $views['pending'] );
$views['trash'] = preg_replace( '/\(.+\)/U', ''.$trash.'', $views['trash'] );
return $views;
}
I know that the issue is that certain parameters aren't found in the db (for example, there may not be any "pending" posts) so it throws out an error. How can I code my way around this, for example, to say, if the parameter exists...
The goal here is to remove the '(' ')' brackets from post counts in wordpress. So when you are on the view posts, or view pages screen, there is a sub menu above the lists of posts/pages with the following items 'all', 'published', 'trash', 'pending' - these are filters that the user can click on. Next to each filter is a number, the number of posts/pages within that filter. The format of this count is ([NUMBER]) - This code is to simply get rid of those brackets.
I noticed by google'ing a bit that you're using the code form this Wordpress SE answer. This doesn't match your needs, as this code is here to recalculate the number of posts after some manipulation on that by the OP.
To just remove the parenthesis, look at the following function in class-wp-list-table.php:
public function views() {
$views = $this->get_views();
$views = apply_filters( "views_{$this->screen->id}", $views );
if ( empty( $views ) )
return;
$this->screen->render_screen_reader_content( 'heading_views' );
echo "<ul class='subsubsub'>\n";
foreach ( $views as $class => $view ) {
$views[ $class ] = "\t<li class='$class'>$view";
}
echo implode( " |</li>\n", $views ) . "</li>\n";
echo "</ul>";
}
This is the function that build the user menu that you try to change. If you look closer at this, you will see that the $view being echo'ed come from a $views that is being filtered previously:
$views = apply_filters( "views_{$this->screen->id}", $views )
$this->screen->id stand for the ID of the current screen, like edit-post for example.
So by adding this simple filter you will achieve what you want to do here:
add_filter('views_edit-post', 'remove_count_parenthesis', 10, 1);
function remove_count_parenthesis($views) {
foreach($views as $key => $view) {
$views[$key] = str_replace(array('(', ')'), '', $view);
}
return $views;
}
You need to check if there is a value 'draft' in your array
if (isset( $views['draft'] )) {
$views['draft'] = preg_replace( '/\(.+\)/U', ''.$draft.'', $views['draft'] );
}
I am making a search function for searching products in woocommerce.
SO URL will be like "http://localhost/wp/?s=123&post_type=product".
User will search anything website will be searched and additionally product's custom field will be searched. This code work fine with http://localhost/wp/?s=123 but when "http://localhost/wp/?s=123&post_type=product is entered in url then it say No product is found.
Code is given below
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace("/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
$where .= " AND ($wpdb->posts.post_type = 'product') ";
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
So What modification is required?
URL http://localhost/wp/?orderby=date&post_type=product work fine
You write $wpdb->posts in "",thats why its not working.
You check it below.
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace("/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
$where .= " AND (".$wpdb->posts.".post_type = 'product') ";
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
I am using this code to search products from a Wordpress/WooCommerce website.
My requirment is URL will be like "http://localhost/wp/?s=D34&post_type=product"
While s=D34 is search string.
When user will search for a string. Data will be searched from All default fields+ product's custom filed. The below code work fine with http://localhost/wp/?s=D34 but when &post_type=product is concatenated with url then it say
Code is given below
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace("/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
$where .= " AND ($wpdb->posts.post_type = 'product') ";
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
This is to prevent distinct values
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT"; //to prevent duplicates
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
So What modification is required?
URL http://localhost/wp/?orderby=price&post_type=product work fine
but what is wrong with http://localhost/wp/?s=D34&post_type=product
try this
function cf_search_where( $where ) {
global $pagenow, $wpdb;
// a little debugging will help you..
//print_r ($where);
//die();
if ( is_search() ) {
$where = preg_replace("/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
$where .= " AND ($wpdb->posts.post_type = 'product') ";
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
Based on your updated question.
if only you've used print_r ($where); to check what value does $where contains, you will see something like these...
with http://localhost/wp/?s=D34
AND (((wp1_posts.post_title LIKE '%D34%') OR (wp1_postmeta.meta_value LIKE '%D34%') OR (wp1_posts.post_content LIKE '%D34%')))
AND (wp1_posts.post_password = '')
AND wp1_posts.post_type IN ('post', 'page', 'attachment', 'product')
AND (wp1_posts.post_status = 'publish')
with http://localhost/wp/?s=D34&post_type=product
AND (((wp1_posts.post_title LIKE '%D34%') OR (wp1_postmeta.meta_value LIKE '%D34%') OR (wp1_posts.post_content LIKE '%D34%')))
AND (wp1_posts.post_password = '')
AND ( ( wp1_postmeta.meta_key = '_visibility' AND CAST(wp1_postmeta.meta_value AS CHAR) IN ('visible','search') ) )
AND wp1_posts.post_type = 'product'
AND (wp1_posts.post_status = 'publish')
take note of wp1_posts.post_type and get a hint.. be flexible on yourself and try to debug. above are results without the $where .= " AND ($wpdb->posts.post_type = 'product') "; though.
I have the following in my functions.php file. I'm trying to return a metavalue(s) for a custom post.
add_action( 'transition_post_status', 'a_new_post', 10, 3 );
function a_new_post( $new_status, $old_status, $post ) {
if ( 'publish' !== $new_status or 'publish' === $old_status )
return;
if ( 'post' == $post->jobman_job )
return; // all of the above is just to trigger the below when my custom post is published
global $wpdb;
$post_id = $post->ID;
$meta_key_value = 'data19';
$table_name = $wpdb->prefix . 'postmeta';
$result = $wpdb->get_results("SELECT meta_value FROM " . $table_name . " WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key_value);
var_dump ($result); // I'm getting NULL
}
When I use a different query and hardcode the values for $post_id and $meta_key_value into it... I get my result as expected. For some reason, the above query will not accept my variables! Can anybody assist?
I've been looking for a way to count the number of custom posts a user has created, and was able to do it using this snippet:
<?php
$userid = get_current_user_id();
function count_user_posts_by_type($userid, $post_type = 'foo_type', $post_status = 'publish') {
global $wpdb;
$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND post_type = '$post_type' AND post_status = '$post_status'";
$count = $wpdb->get_var($query);
return apply_filters('get_usernumposts', $count, $userid);
} ?>
And then echo the result with:
<?php echo count_user_posts_by_type($userid); ?>
My question: Above code outputs only the count of the custom post type "foo_type". If I have two custom post types - "foo_type" and "bar_type" - how do I change this code so that it returns the count of both of them rather than just the count of "foo_type"?
Add the second post_type to the query:
$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND (post_type = '$post_type' OR post_type='$post_type_2') AND post_status = '$post_status'";
Try custom function given below
function my_count_posts_by_user($post_author=null,$post_type=array(),$post_status=array()) {
global $wpdb;
if(empty($post_author))
return 0;
$post_status = (array) $post_status;
$post_type = (array) $post_type;
$sql = $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = %d AND ", $post_author );
//Post status
if(!empty($post_status)){
$argtype = array_fill(0, count($post_status), '%s');
$where = "(post_status=".implode( " OR post_status=", $argtype).') AND ';
$sql .= $wpdb->prepare($where,$post_status);
}
//Post type
if(!empty($post_type)){
$argtype = array_fill(0, count($post_type), '%s');
$where = "(post_type=".implode( " OR post_type=", $argtype).') AND ';
$sql .= $wpdb->prepare($where,$post_type);
}
$sql .='1=1';
$count = $wpdb->get_var($sql);
return $count;
}
And then echo the result with:
<?php echo my_count_posts_by_user($userid , array('posttype1' , 'posttype2')); ?>
Please look on url given below..
https://wordpress.stackexchange.com/questions/43549/count-user-posts-by-user-id-post-type-and-post-status
thanks
$args = array(
'post_type'=> 'page',
'author' => '1',
'post_staus'=> 'publish',
'posts_per_page' => -1
);
echo custom_count_post_by_author($args);
function custom_count_post_by_author($args){
query_posts( $args );
$count = 0;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$count++;
endwhile;
endif;
wp_reset_query();
return $count;
}
You can pass any Arguments in $args which support query_posts