Wordpress undefined index issue php - php

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'] );
}

Related

Shortcode attributes that query the database

I am trying to create a shortcode that returns a list of doctors matching a specialty.
So far, I can get the base shortcode to return the contents of the entire table, but I can't get it to query based on an attribute string.
Here's what I have:
// Add Shortcode
function list_docs( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'specialty' => '',
),
$atts,
'doctors'
);
global $wpdb;
$specialty = $atts['specialty'];
$specget = $wpdb->prepare("SELECT * FROM doctors WHERE specialty = '%s'", $specialty);
$specresults = $wpdb->get_results($specget);
foreach($specresults as $details) {
echo $details;
}
}
add_shortcode( 'doctors', 'list_docs' );
If I query the database directly with:
SELECT * FROM `doctors` WHERE `specialty` = 'cardiology'
I get the expected result.
I'm trying to call it with [doctors specialty="cardiology"] (I've tried double and single quotes) on the WordPress page.
Right now, I don't know what I don't know. I'm not sure if I've entered something wrong, have a typo, or am missing a line of code. Any assistance would be terrific.
May be problem is not with the query at all assuming that your table name is indeed doctors( & not wp_doctors or something like that )
$specresults will contain an array of objects. Let's say your doctors table has name column, then below changes may work for you.
function list_docs( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'specialty' => '',
),
$atts,
'doctors'
);
global $wpdb;
$specialty = $atts['specialty'];
$specget = $wpdb->prepare( 'SELECT * FROM doctors WHERE specialty = %s', $specialty );
$specresults = $wpdb->get_results( $specget );
if ( $specresults ) {
$doctor_names = array_map(
function( $doctor_object ) {
return $doctor_object->name;
},
$specresults
);
return implode( ', ', $doctor_names );
}
return '';
}
add_shortcode( 'doctors', 'list_docs' );
Couple of things to keep in mind:-
Shortcodes should always return & not echo directly.
Query only for required data from the database as far as possible instead of doing *
If you are going to need only one column, prefer using get_col method on $wpdb instead of get_results.
Please try with this -
function list_docs( $atts ) {
global $wpdb;
$specialty = $atts['specialty'];
$specget = $wpdb->prepare("SELECT * FROM doctors WHERE specialty = %s", $specialty);
$specresults = $wpdb->get_results($specget);
foreach($specresults as $details) {
echo $details;
}
}
add_shortcode( 'doctors', 'list_docs' );

if logic in posts_where not working wordpress

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?

Get authors post in wordpress with co-author plus installed

I want to list all posts, a user is assigned as author.
We are using the plugin, co-authors plus, which allows to assign multiple authors to a single post.
The function <?php $user_post_count = count_user_posts( $userid ); ?> returns the correct number of posts, the user is assigned to.
But when trying to list all the posts, with The loop only the post which initially were created by that user are shown.
query_posts( $args );
if (count_user_posts($user->ID) == 0) {
echo "No posts";
}
// The Loop
while ( have_posts() ) : the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
Is there an other possibility to get all posts from an user or can we modify our existing code?
EDIT
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'author',
'field' => 'slug',
'terms' => $user_login
)
),
);
$author_query = new WP_Query( $args );
if ( $author_query->have_posts() ) :
while ( $author_query->have_posts() ) : $author_query->the_post();
// Do your presentation
endwhile;
endif;
/**
* #param $user_id
* #param int $paged (if $paged = null return all posts)
* #return array|bool
*/
function get_coauthor_posts_by_author_id($id, $paged = 1)
{
global $wpdb;
$slug = 'cap-' . strtolower(get_userdata($id)->user_nicename);
$max_post = get_option('posts_per_page');
$post_lower_limit = 0;
if ($paged > 1) {
$post_upper_limit = $max_post * $paged;
$post_lower_limit = $post_upper_limit - $max_post;
}
$term_id = $wpdb->get_results($wpdb->prepare("SELECT term_id FROM $wpdb->terms WHERE slug = %s ", $slug))[0]->term_id;
$sql = "SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.id FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships AS tr1 ON ($wpdb->posts.id = tr1.object_id) LEFT JOIN $wpdb->term_taxonomy ON ( tr1.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id ) WHERE 1=1 AND (($wpdb->posts.post_author = %d OR ($wpdb->term_taxonomy.taxonomy = 'author' AND $wpdb->term_taxonomy.term_id = %d))) AND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'private') GROUP BY $wpdb->posts.id ORDER BY $wpdb->posts.post_date DESC";
$sql_limit = " LIMIT %d, %d";
if ($paged !== null) {
$sql = $sql . $sql_limit;
}
$result = $wpdb->get_results($wpdb->prepare($sql, $id, $term_id, $post_lower_limit, $max_post), ARRAY_A);
return array_column($result, 'id');
}

Handle search in Wordpress from WP_List_Table code

I need to add support for searching or filter items using WP_List_Table I read and didn't know how to get this done. I've already added the box trough this code:
function ft_list()
{
echo '</pre><div class="wrap"><h2>' . __('Frequent Traveler List') . '</h2>';
$ftList = new FT_WP_Table();
$ftList->search_box('search', 'search_id');
echo '</div>';
}
And this is how my prepare_items() functions looks:
public function prepare_items()
{
$searchcol = array(
'firstname',
'lastname',
'foid',
'no_frequent',
'create_time'
);
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array(
$columns,
$hidden,
$sortable
);
// SQL results
$posts = $this->get_sql_results();
empty($posts) AND $posts = array();
# >>>> Pagination
$per_page = $this->posts_per_page;
$current_page = $this->get_pagenum();
$total_items = count($posts);
$this->set_pagination_args(array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items / $per_page)
));
$last_post = $current_page * $per_page;
$first_post = $last_post - $per_page + 1;
$last_post > $total_items AND $last_post = $total_items;
// Setup the range of keys/indizes that contain
// the posts on the currently displayed page(d).
// Flip keys with values as the range outputs the range in the values.
$range = array_flip(range($first_post - 1, $last_post - 1, 1));
// Filter out the posts we're not displaying on the current page.
$posts_array = array_intersect_key($posts, $range);
# <<<< Pagination
// Prepare the data
$permalink = __('Edit:');
foreach ($posts_array as $key => $post) {
$link = get_edit_post_link($post->id);
$no_title = __('No title set');
$title = !$post->firstname ? "<em>{$no_title}</em>" : $post->firstname;
$posts[$key]->firstname = "<a title='{$permalink} {$title}' href='{$link}'>{$title}</a>";
}
$this->items = $posts_array;
}
Where I should add the code to filter items based on search parameter?
Looking at other classes that extend WP_List_Table I see they use something like
$search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : false;
and pass that to the prepare_items() method.
In my test plugin I made this (see Percent in wpdb->prepare):
$search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : false;
$do_search = ( $search ) ? $wpdb->prepare(" AND post_content LIKE '%%%s%%' ", $search ) : '';
$sql_results = $wpdb->get_results("
SELECT $sql_select
FROM $wpdb->posts
WHERE post_status = 'publish'
$do_search
ORDER BY $this->orderby $this->order "
);
And in display_tablenav() method I added:
<form action="" method="GET">
<?php
$this->search_box( __( 'Search' ), 'search-box-id' );
?>
<input type="hidden" name="page" value="<?= esc_attr($_REQUEST['page']) ?>"/>
</form>
I haven't created any search_box() method, letting the parent class render it.

WordPress count user posts of different custom post types

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

Categories