I have a script that displays users who have published on my site.... Im wondering how I can set the limit that is shown to 10.. I'm new to PHP.. Would I be able to use a foreach to achieve this?
<?php
// Display the widget title
if ( $title ) {
echo $before_title . $title . $after_title;
}
$args = array(
'role' => $role,
'orderyby' => 'post_count',
'order' => 'DESC'
);
$user_ids = get_users($args);
foreach ($user_ids as $user_id) {
if ($postcount) {
if(count_user_posts($user_id->ID)>0) {
echo '<a class="cuda-gravatar" href="'.get_author_posts_url($user_id->ID).'" title="'.$user_id->display_name.'">';
echo get_avatar($user_id->ID, $size);
echo '</a>';
} else {
}
} else {
echo '<a class="cuda-gravatar" href="'.get_author_posts_url($user_id->ID).'" title="'.$user_id->display_name.'">';
echo get_avatar($user_id->ID, $size);
echo '</a>';
}
}
You may try this (number):
$args = array(
'role' => $role,
'orderyby' => 'post_count',
'order' => 'DESC',
'number' => 10 // <-- add this
);
You may also use offset, read more on Codex about get users().
The classic way would be to set a limit to your sql query
$args = array(
...
'posts_per_page' => 10
);
or your can add a counter
foreach ($user_ids as $user_id) {
$i++
...
if($i==10){break;}
}
Related
How to check if the post exists before wp_insert_post to avoid duplication?
The code below works if I remove the 'if' statement (post_exists()) and just keep reinserting posts producing multiple duplications. I wrote the if-statement with post_exists() just to start implementing the logic of checking but the moment I add the if statement, something breaks and the list below doesn't even get printed.
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'exists';
} else {
echo 'doesnt exist';
}
echo '<li>';
echo $event['id'];
echo '' . $event['name'] . '';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
?>
Edit: please see the $data_events array:
https://pastebin.com/rC60iNyJ
The post_exists() function is not normally available on the front end. Instead of including another file you can use get_page_by_title to find a post by it's title. Just test for a null value to check if it doesn't exist.
Replace
if ( post_exists( $event['name'] ) == 0 ) {
with
if ( get_page_by_title( $event['name'] ) == null ) {
Try this code. you need to include this file.
because post_exists function will work on admin page not in frontend.
if ( ! is_admin() ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'doesnt exist';
} else {
echo 'exists';
}
echo '<li>';
echo $event['id'];
echo '' . $event['name'] . '';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
I'm using this code...
function include_post_types() {
$post_types = get_post_types( array (
'show_ui' => true
),
'objects' );
$return = '';
foreach ( $post_types as $post_type ) {
$my_sitemap_options = get_option( 'my_sitemap_settings' );
$post_type_name = $post_type->name;
if ($my_sitemap_options['post_types'] && in_array($post_type_name, $my_sitemap_options['post_types'])) {
$the_excluded = $post_type_name;
$return .= "'" . $the_excluded . "', ";
}
}
return $return;
}
... to return a list of custom post types that I have selected from an options page. This works fine, and if I do this...
echo included_post_types();
...I see this...
'clothes', 'shoes', 'jackets',
...which is what I excpected.
But the problem is when I try to use included_post_types() in a loop to only show posts with those post types, like this:
$sitemap_post_args = array(
'post_type' => array(included_post_types()),
'posts_per_page' => -1,
'orderby' =>'post_type',
'order' =>'asc'
);
$loop = new WP_Query($sitemap_post_args);
global $post_type;
global $post;
echo '<ul>';
$last_post_type = '';
while($loop->have_posts()): $loop->the_post();
$current_post_type = $post->post_type;
$current_post_type_object = get_post_type_object( $current_post_type );
if($current_post_type != $last_post_type) echo "<br /><li><strong>" . $current_post_type_object->labels->name . "</strong></li>";?>
<li><?php echo get_the_title(); ?></li>
<?php echo "\n";
$last_post_type = $current_post_type;
endwhile;
wp_reset_query();
echo '</ul>';
It simply doesn't display anything on my page, but it doesn't throw an error either.
I'm almost certain the problem is this line:
'post_type' => array(included_post_types()),
I even tried it like this...
'post_type' => included_post_types(),
...but it did not work.
If I try this...
'post_type' => array('clothes', 'shoes', 'jackets', ),
...it works, but I need to be able to use the function name.
Any suggestions would be helpful.
please replace below code with yours. It should be help.
function include_post_types() {
$post_types = get_post_types( array (
'show_ui' => true
),
'objects' );
$return = array();
foreach ( $post_types as $post_type ) {
$my_sitemap_options = get_option( 'my_sitemap_settings' );
$post_type_name = $post_type->name;
if ($my_sitemap_options['post_types'] && in_array($post_type_name, $my_sitemap_options['post_types'])) {
$the_excluded = $post_type_name;
$return[] = $the_excluded;
}
}
return $return;
}
and also replace below code that show posts
$post_type_list = include_post_types();
$sitemap_post_args = array(
'post_type' => $post_type_list,
'posts_per_page' => -1,
'orderby' =>'post_type',
'order' =>'asc'
);
I cannot use the 'orderby' => 'post_count' as contributors have multiple posts assigned to them.
Rather, for each user output, I get their $post_count using the count_user_posts() function.
How can I re-order the items based on this number? Highest to lowest?
The user post count is not part of the $users array :(
// order contributors
$args = array(
'role' => contributors,
'orderby' => 'post_count',
'order' => 'ASC',
'fields' => 'all'
);
// The Query
$user_query = new WP_User_Query( $args );
$users = $user_query->get_results();
echo '<ul>';
$i = 0;
foreach ( $users as $user ) {
$post_count = count_user_posts( $user->id );
if ( count_user_posts( $user->id ) >= 1 ) {
echo '<li class="ws-sort" data-sort="' . $post_count . '"><a href="' . site_url() . '/author/' . $user->user_nicename . '">' . $user->display_name . '</li>';
if (++$i == 8) break;
}
}
echo '</ul>';
You can use usort with a custom function:
usort($users, function(&$a,&$b) {
if (!isset($a->_post_count)) $a->_post_count = count_user_posts( $a->id );
if (!isset($b->_post_count)) $b->_post_count = count_user_posts( $b->id );
return $a->_post_count < $b->_post_count;
});
And you can also use _post_count in the other foreach, since the sorting modified each element ( $a and $b are passed by reference )
I have a form that allows a user to select a county from a dropdown menu, My form is then posted to my functions.php page where I've been using IF statements to run my queries.
if ($_POST['dropdown1'] == 'option 1' && $_POST['dropdown 2'] == 'option 4' && $_POST['county'] == 'cheshire' ) {
// RUN QUERY
}
My problem is however I can't realistically use IF statements for every county in every possible scenario as there will be thousands of options, has anybody got a better idea of how I can do this?
if ($_POST['vehicleType'] == 'hgv' && $_POST['coverageRegion'] == 'national' ) {
$customkey = 'vehicleType';
$customvalue = $_POST['vehicleType'];
$customkey1 = 'coverageRegion';
$customvalue1 = $_POST['coverageRegion'];
$customkey2 = 'locationType';
$customvalue2 = $_POST['locationType']; $args = array('orderby' => 'meta_value_num', 'meta_key' => 'order', 'order' => 'ASC',
'meta_query' => array(
array(
'key' => $customkey,
'value' => $customvalue,
'compare' => '='
),
array(
'key' => $customkey1,
'value' => $customvalue1,
'compare' => '='
),
array(
'key' => $customkey2,
'value' => $customvalue2,
'compare' => '='
)
) // end of array
); //end of if
$query = new WP_Query( $args);
// The Loop
$i = 0; $i = -1;
while ( $query->have_posts() )
{
$i++;
$query->the_post();
if ( $keys = get_post_custom_keys() )
{
echo "<div class='clearfix card-prod ".($i==0?'first':'')."'><div class='top-dets'><span class='card-title'>";
echo the_title();
echo "</span>";
// Network query
$network_value = get_post_custom_values('srchnetwork');
foreach ( $network_value as $key => $value ) {
echo '<span class="srch-val-">'. $value . '</span>'; }// Pricing Query
$pricing_value = get_post_custom_values('srchpricing');
foreach ( $pricing_value as $key => $value ) {
echo '<span class="srch-val-1">'. $value . '</span>'; }
// Setup Query
$setup_value = get_post_custom_values('srchsetupfee');
foreach ( $setup_value as $key => $value ) {
echo '<span class="srch-val-2">'. $value . '</span>'; }
// Services Query
$services_value = get_post_custom_values('srchservices');
foreach ( $services_value as $key => $value ) {
echo '<span class="srch-val-3">'. $value . '</span></div>'; }
// Big Card Query
$bigcard_value = get_post_custom_values('bigcard');
foreach ( $bigcard_value as $key => $value ) {
echo '<a href="/" class="cardclick"><img src="/wp-content/themes/CAFC/images/cards/'. $value . '" alt="'; }
echo the_title() . '" /></a>';
echo '<img src="wp-content/themes/CAFC/images/top-choice.jpg" alt="Top Choice" class="topchoice">';
echo the_excerpt()."</div>"; }
}
}
You can write your code in this way so you don't have to deal with every possible option.
global $wpdb;
$postKeys = array('vehicleType', 'coverageRegion', 'locationType');
$args = array(
'orderby' => 'meta_value_num',
'meta_key' => 'order',
'order' => 'ASC',
'meta_query' => array()
);
foreach ($postKeys as $key) {
$args['meta_query'][] = array(
'key' => $key,
'value' => $wpdb->escape($_POST[$key]),
'compare' => '='
);
}
$query = new WP_Query($args);
I am working on a Wordpress-Design and i want to creat a Custom Menu.
$items = wp_get_nav_menu_items('Menu', array(
'order' => 'ASC',
'orderby' => 'menu_order',
'post_type' => 'nav_menu_item',
'post_status' => 'publish',
'output' => ARRAY_A,
'output_key' => 'menu_order',
'nopaging' => true,
'update_post_term_cache' => false));
echo '<pre>'; print_r($items); echo '</pre>';
foreach($items as $item){
echo '<div class="menu_entry">'.$item->title.'</div>';
}
The problem is, i need the "current-page"-Class, which is WordPress creating - in the Standard Menu.
Any Ideas how to add this class?
Solution time:
WordPress's function that adds these classes is _wp_menu_item_classes_by_context(). This is called already when you use wp_nav_menu but not wp_get_nav_menu_items. Fortunately, the latter provides a filter so we can do it ourselves:
add_filter( 'wp_get_nav_menu_items', 'prefix_nav_menu_classes', 10, 3 );
function prefix_nav_menu_classes($items, $menu, $args) {
_wp_menu_item_classes_by_context($items);
return $items;
}
You can do a compare on the current page / cat etc ID against the menu items object_id which is the ID of the page / category etc its linked to.
Something like (untested);
global $post;
$thePostID = $post->ID;
foreach($items as $item){
if($thePostID === $item->object_id) {
echo '<div class="menu_entry">'.$item->title.'</div>';
}else{
echo '<div class="menu_entry">'.$item->title.'</div>';
}
}
Using the function get_queried_object_id(). This works fine in all the pages, including the Blog page.
See an example:
if ( $menu_items = wp_get_nav_menu_items( 'menu' ) ) {
foreach ( $menu_items as $menu_item ) {
$current = ( $menu_item->object_id == get_queried_object_id() ) ? 'current' : '';
echo '<li class="' . $current . '">' . $menu_item->title . '</li>';
}
}