Count wordpress post hits - wordpress

I want to count and show WordPress posts in admin panel.I don't want to show it on the website but I want to be able to sort posts in admin panel according to their hits.
I used this link to do so. Every thing is good but it only doesn't sort the posts. In the source website it has told to put some code in template.js. But I don't know where is this file.
functions.php
/*
Function: getPostViews (custom)
Gets the Post Views count
Returns:
$count.' Views'
*/
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
/*
Function: setPostViews (custom)
Sets the Post Views count
*/
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
template.js
// get querystring as an array split on "&"
var querystring = location.search.replace( '?', '' ).split( '&' );
// declare object
var queryObj = {};
// loop through each name-value pair and populate object
for ( var i=0; i<querystring.length; i++ ) {
// get name and value
var name = querystring[i].split('=')[0];
var value = querystring[i].split('=')[1];
// populate object
queryObj[name] = value;
}
// Check query string for sort filter method
if(queryObj[ "filter" ] === "popular"){
$('#newest').removeClass('active');
$('#popular').addClass('active');
} else if(queryObj[ "filter" ] === "newest"){
$('#popular').removeClass('active');
$('#newest').addClass('active');
}
Wordpress Post Sorting
<?
// Place this code into your archive.php template file
$filter = $_GET['filter'];
// Preserve existing query parameters
global $wp_query;
// Check query string parameter "filter" (options: 'popular' and 'newest')
if((isset($filter)) && $filter == 'popular'){
$args = array_merge( $wp_query->query, array('order' => 'desc', 'orderby' => 'meta_value_num', 'meta_key' => 'post_views_count') );
query_posts( $args );
}else if((isset($filter)) && $filter == 'newest'){
$args = array_merge( $wp_query->query, array('order' => 'desc') );
query_posts( $args );
}
?>

Related

load my user_login from database into my acf select field code

I am trying to upload my user_login from database into acf select field, in var_dump my array result is working good, but nothing uploaded in my acf select field?
1. I added a custom field "ACF select field" in a product post.
2. I'm trying to load my options values from my database.
3. I used an array to get the user_login values from the database
function.php
add_filter('acf/load_field/name=chef', 'my_acf_load_chef_field');
function my_acf_load_chef_field( $field )
{
$user_fields = array( 'user_login');
$argu = new WP_User_Query( array( 'role' => 'chef' , 'fields' => $user_fields ));
$choices = $argu->get_results();
$field = array();
if( is_array($choices) ) {
$len = count($choices);
for($i = 0; $i < $len; $i++) {
array_push($field, ($choices[$i]->user_login));
}
}
// var_dump($field);
// exit;
return $field;
}
this is the var_dump result
array(5) {
[0]=> string(5) "Ahmed"
[1]=> string(5) "Khedr"
[2]=> string(4) "meme"
[3]=> string(5) "Menna"
[4]=> string(7) "mustafa" }
this is the array result that i want to load in acf field
i found it
this is the new code
thanks justkidding96
add_filter('acf/load_field/name=chef', 'my_acf_load_chef_field');
function my_acf_load_chef_field( $field )
{
$user_fields = array( 'user_login');
$argu = new WP_User_Query( array( 'role' => 'chef' , 'fields' => $user_fields ));
$choices = $argu->get_results();
//$choices = get_field($field['choices'], $post->ID , false);
$field['choices'] = array();
if( is_array($choices) ) {
$len = count($choices);
for($i = 0; $i < $len; $i++) {
array_push($field['choices'], ($choices[$i]->user_login));
}
}
// var_dump($field['choices']);
// exit;
return $field;
Your don’t assign your choices to the field. Try this code:
if (is_array($choices)) {
// Clear the choices
$field[‘choices’] = [];
// Assign the data to the field
foreach ($choices as $choice) {
$field[‘choices’][$choice->user_login] = $choice->user_login;
}
}

How can I filter posts when the meta_value is a serialize object?

I'm doing a dropdown in my post custom type just to filter the content when is completed or not.
my meta_value is a serialize object like "a:3:{s:5:"email";s:21:"mrsxcvsfesr#gmail.com";s:9:"store";s:6:"testes";s:5:"token";s:34:"$P$B7efpLZUWWyB4QkhG0YaYyIwXRAj.3.";}"
and my job is to check if the token is null or not
CustomPostTypeController.php
add_action('restrict_manage_posts',[ $this, 'dropdown_status_filter']);
add_filter( 'parse_query', [ $this, 'filter_request_query'])
public function dropdown_status_filter($post_type){
if('ctp_dasboard' !== $post_type) {
return; //filter your post
}
$selected = '';
$request_attr = 'status_filter';
if ( isset($_REQUEST[$request_attr]) ) {
$selected = $_REQUEST[$request_attr];
}
echo '<select id="status_filter-loc" name="status_filter">';
echo ($selected === '1') ? "'<option value='1' selected>Done</option>'" : "'<option value='1'>Done</option>'";
echo ($selected === '2') ? "'<option value='2' selected>Pending</option>'" : "'<option value='2'>Pending</option>'";
echo '</select>';
}
public function filter_request_query($query){
//modify the query only if it admin and main query.
if( !(is_admin() AND $query->is_main_query()) ){
return $query;
}
//we want to modify the query for the targeted custom post and filter option
if( !('ctp_dasboard' === $query->query['post_type'] AND isset($_REQUEST['status_filter']) ) ){
return $query;
}
//for the default value of our filter no modification is required
if(0 == $_REQUEST['status_filter']){
return $query;
}
//modify the query_vars.
// $value = "";
// var_dump($_REQUEST['status_filter'] === '1');
if ( $_REQUEST['status_filter'] === '1'){
// global $wpdb;
// $meta_key = 'form_ctp';
// $meta_value = '"token";N;';
// $mid = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value LIKE %s ", $meta_key, $meta_value) );
// dd($mid);
// // The Query
$args = [
'post_type' => 'ctp_dasboard',
['meta_query' => [
'key' => 'form_ctp',
'value' => 'token";N;', // this is when token is null
'compare' => 'IN'
]]
];
// dd($args);
$query = new \WP_Query( $args );
// dd($the_query);
}
if ( $_REQUEST['status_filter'] === '2'){
}
return $query;
}
There is a special function maybe_unserialize which can return you unserialized data array/ string and etc. Check documentation. Your variable should look like this:
$str = "a:3{s:5:"email";s:21:"mrsxcvsfesr#gmail.com";s:9:"store";s:6:"testes";s:5:"token";s:34:"$P$B7efpLZUWWyB4QkhG0YaYyIwXRAj.3.";}";
$data = maybe_unserialize($str); // will return an array

WordPress - Get Current Post Author ID Outside The Loop And Inside A Plugin

I am trying to modify a plugin. I need the author id of the current post to accomplish what I am doing. I have tried every other method I have found over internet that claims to get the post author id outside the loop but its not working inside the plugin. I guess its because the plugins might be loaded before the loop variables or something? Please pardon me as I am not a Pro.
Here is what I have tried so far.
1.
$author_id=$post->post_author;
2.
global $post;
$author_id=$post->post_author;
3.
$post_tmp = get_post($post_id);
$author_id = $post_tmp->post_author;
4.
$author_id = $posts[0]->post_author;
But nothing works in the plugin's directory. Can anyone help?
Detailed Explanation:
I am trying to modify woodiscuz plugin. The problem with this plugin is that it held comments of even seller for moderation. So if I am the seller and I reply to some buyer in comment, I will have to approve my own comment.
Now to overcome this problem, I am putting a condition that if the author of the post (seller) is commenting, then don't put the comment for moderation.
Here is the function of the plugin that is controlling comments.
public function comment_submit_via_ajax() {
$message_array = array();
$comment_post_ID = intval(filter_input(INPUT_POST, 'comment_post_ID'));
$comment_parent = intval(filter_input(INPUT_POST, 'comment_parent'));
if (!$this->wpc_options->wpc_options_serialized->wpc_captcha_show_hide) {
if (!is_user_logged_in()) {
$sess_captcha = $_SESSION['wpc_captcha'][$comment_post_ID . '-' . $comment_parent];
$captcha = filter_input(INPUT_POST, 'captcha');
if (md5(strtolower($captcha)) !== $sess_captcha) {
$message_array['code'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_captcha'];
echo json_encode($message_array);
exit;
}
}
}
$comment = filter_input(INPUT_POST, 'comment');
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$user = get_userdata($user_id);
$name = $user->display_name;
$email = $user->user_email;
$user_url = $user->user_url;
} else {
$name = filter_input(INPUT_POST, 'name');
$email = filter_input(INPUT_POST, 'email');
$user_id = 0;
$user_url = '';
}
$comment = wp_kses($comment, array(
'br' => array(),
'a' => array('href' => array(), 'title' => array()),
'i' => array(),
'b' => array(),
'u' => array(),
'strong' => array(),
'p' => array(),
'img' => array('src' => array(), 'width' => array(), 'height' => array(), 'alt' => array())
));
$comment = $this->wpc_helper->make_clickable($comment);
if ($name && filter_var($email, FILTER_VALIDATE_EMAIL) && $comment && filter_var($comment_post_ID)) {
$held_moderate = 1;
if ($this->wpc_options->wpc_options_serialized->wpc_held_comment_to_moderate) {
$held_moderate = 0;
}
// $held_moderate = 1 -> No moderation
/*This is the part where I need to put the custom condition*/
if($post_author_id == get_current_user_id())
{
$held_moderate = 1;
}
$new_commentdata = array(
'user_id' => $user_id,
'comment_post_ID' => $comment_post_ID,
'comment_parent' => $comment_parent,
'comment_author' => $name,
'comment_author_email' => $email,
'comment_content' => $comment,
'comment_author_url' => $user_url,
'comment_type' => 'woodiscuz',
'comment_approved' => $held_moderate
);
$new_comment_id = wp_insert_comment($new_commentdata);
$new_comment = new WPC_Comment(get_comment($new_comment_id, OBJECT));
if (!$held_moderate) {
$message_array['code'] = -2;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_held_for_moderate'];
} else {
$message_array['code'] = 1;
$message_array['message'] = $this->comment_tpl_builder->get_comment_template($new_comment);
}
$message_array['wpc_new_comment_id'] = $new_comment_id;
} else {
$message_array['code'] = -1;
$message_array['wpc_new_comment_id'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_field'];
}
echo json_encode($message_array);
exit;
}

change the number of results per page in drupal views

I need to have an option on my search page which will allow the users to select the number of results that they want to display in the view i.e 25 results, 50 , 100 results per page. My theme_pager code is
function theme_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 9) {
global $pager_page_array, $pager_total;
$tags = array("", "< prev", "", "next >", "");
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$ pager_middle = ceil($quantity / 2);
// current is the page we are currently paged to
$pager_current = $pager_page_array[$element] + 1;
// first is the first page listed by this pager piece (re quantity)
$pager_first = $pager_current - $pager_middle + 1;
// last is the last page listed by this pager piece (re quantity)
$pager_last = $pager_current + $quantity - $pager_middle;
// max is the maximum page number
$pager_max = $pager_total[$element];
// End of marker calculations.
// Prepare for generation loop.
$i = $pager_first;
if ($pager_last > $pager_max) {
// Adjust "center" if at end of query.
$i = $i + ($pager_max - $pager_last);
$pager_last = $pager_max;
}
if ($i <= 0) {
// Adjust "center" if at start of query.
$pager_last = $pager_last + (1 - $i);
$i = 1;
}
// End of generation loop preparation.
$view = views_get_current_view();
// ensure view exists
if (!$view) return;
// set object property to return total rows
$view->get_total_rows = true;
// set display_id
$view->set_display($display_id);
// execute view
$view->execute();
// acquire data from views object and $_REQUEST
$itemsPerPage = $view->pager['items_per_page'];
$currentPage = $_REQUEST['page']+1;
$total = $view->total_rows;
// start calculation
$start = ($itemsPerPage * $currentPage) - ($itemsPerPage-1);
$end = $itemsPerPage * $currentPage;
if ($end>$total) $end = $total;
// return html
$x = "<b>Displaying $start - $end of $total</b>";
$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] : t('‹ previous')), $limit, $element, 1, $parameters);
$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('next ›')), $limit, $element, 1, $parameters);
if ($pager_total[$element] > 1) {
$items[] = array(
'class' => 'pager',
'data' => $x,
);
if ($li_previous) {
$items[] = array(
'class' => 'pager-previous',
'data' => $li_previous,
);
}
// When there is more than one page, create the pager list.
if ($i != $pager_max) {
// Now generate the actual pager piece.
for (; $i <= $pager_last && $i <= $pager_max; $i++) {
if ($i < $pager_current) {
if ($pager_first > 1 && $i == $pager_first) {
$output = '...'.$i;
$stopPreEllipsis = true;
} else {
$output = $i;
}
$items[] = array(
'class' => 'pager-item',
'data' => theme('pager_previous', $output, $limit, $element, ($pager_current - $i), $parameters),
);
}
if ($i == $pager_current) {
$items[] = array(
'class' => 'pager-current',
'data' => $i,
);
}
if ($i > $pager_current) {
if ($pager_last < $pager_max && $i == $pager_last) {
$output = $i.'...';
} else {
$output = $i;
}
$items[] = array(
'class' => 'pager-item',
'data' => theme('pager_next', $output, $limit, $element, ($i - $pager_current), $parameters),
);
}
}
}
// End generation.
if ($li_next) {
$items[] = array(
'class' => 'pager-next',
'data' => $li_next,
);
}
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}
As you might have noticed, theme_pager does not call the database, it merely presents the items from the database. It does not even render the items in the list that is paged.
You will therefore need to override the amount before it gets passed into pager_query(). With views, I have no idea. In a custom module it would be really simple: read out an url parameter or POSTed variable and pass that along as second parameter into pager_query(). I suspect views has some hook to override the amount-per-page in runtime, just before it gets passed to the query-builder. But due to the poor documentation of views, it is not easily found.

drupal table with the edit link

I have a table in drupal which displays all the content from a table. I have added an edit link to each record . This link should take the user to the input form which has the values populated in it corresponding to the record. RIght now it is just populating the form with the last row.
For a row x, i need the form populated with the values for record x.
The table is created as
function _MYMODULE_sql_to_table($sql) {
$html = "";
// execute sql
$resource = db_query($sql);
// fetch database results in an array
$results = array();
while ($row = db_fetch_array($resource)) {
$results[] = $row;
$email = $row['p1'];
$comment = $row['p2'];
}
// ensure results exist
if (!count($results)) {
$html .= "Sorry, no results could be found.";
return $html;
}
// create an array to contain all table rows
$rows = array();
// get a list of column headers
$columnNames = array_keys($results[0]);
// loop through results and create table rows
foreach ($results as $key => $data) {
// create row data
$row = array(
'edit' => l(t('Edit'),"admin/content/test/$p1/$p2/Table1", $options=array()),);
// loop through column names
foreach ($columnNames as $c) {
$row[] = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// add row to rows array
$rows[] = $row;
}
// loop through column names and create headers
$header = array();
foreach ($columnNames as $c) {
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// generate table html
$html .= theme('table', $header, $rows);
return $html;
}
// then you can call it in your code...
function _MYMODULE_some_page_callback() {
$html = "";
$sql = "select * from {contactus}";
$html .= _MYMODULE_sql_to_table($sql);
return $html;
}
function display(){
$results = array();
$html = "";
$resource = db_query("select * from contactus");
$output = '';
while($row = db_fetch_array($resource)){
$results[] = $row;
}
if(!count($results)){
$html.= "Unable to display table";
return $html;
}
$rows = array();
$columnNames = array_keys($results[0]);
foreach($results as $key=>$data){
$row = array();
foreach($columnNames as $c){
$row = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
$rows[] = $row;
}
$header = array();
foreach($columnNames as $c){
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
$html .= theme('table', $header, $rows);
return $html;
}
You'll want to have $rows = array(); appear before your while loop. What you're doing is essentially destroying the array and redeclaring it as an empty array on each pass. This is why only the last row is appearing for you.

Resources