Modify Wordpress function get_pagenum_link - php

is there any possiblity that I can change the following link:
xxx.com/page/2
to
xxx.com/?paged=2
Here the current function:
function get_pagenum_link($pagenum = 1) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$request = remove_query_arg( 'paged' );
$home_root = parse_url(home_url());
$home_root = ( isset($home_root['path']) ) ? $home_root['path'] : '';
$home_root = preg_quote( trailingslashit( $home_root ), '|' );
$request = preg_replace('|^'. $home_root . '|', '', $request);
$request = preg_replace('|^/+|', '', $request);
if ( !$wp_rewrite->using_permalinks() || is_admin() ) {
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $pagenum > 1 ) {
$result = add_query_arg( 'paged', $pagenum, $base . $request );
} else {
$result = $base . $request;
}
} else {
$qs_regex = '|\?.*?$|';
preg_match( $qs_regex, $request, $qs_match );
if ( !empty( $qs_match[0] ) ) {
$query_string = $qs_match[0];
$request = preg_replace( $qs_regex, '', $request );
} else {
$query_string = '';
}
$request = preg_replace( "|$wp_rewrite->pagination_base/\d+/?$|", '', $request);
$request = preg_replace( '|^index\.php|', '', $request);
$request = ltrim($request, '/');
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $wp_rewrite->using_index_permalinks() && ( $pagenum > 1 || '' != $request ) )
$base .= 'index.php/';
if ( $pagenum > 1 ) {
$request = ( ( !empty( $request ) ) ? trailingslashit( $request ) : $request ) . user_trailingslashit( $wp_rewrite->pagination_base . "/" . $pagenum, 'paged' );
}
$result = $base . $request . $query_string;
}
$result = apply_filters('get_pagenum_link', $result);
return $result;
}
from wordpress-includes/link-template.php
How I can modify the function without editing it in the core?
Thanks

From the source, it looks like you should just be able to disable permalinks to get it to page like that.
//start of function code
// ...
if ( !$wp_rewrite->using_permalinks() || is_admin() ) {
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $pagenum > 1 ) {
$result = add_query_arg( 'paged', $pagenum, $base . $request );
} else {
$result = $base . $request;
}
}
//rest of function code
// ...
Docs for add_query_arg()

Related

Run a function inside a worpress shortcode php function

I am trying to create a shortcode to connect to an API but there is a problem with the shortcode. I know that it is because a function is inside a functinon but I can't figure out how to fix. I tried something that didn't work.
// Add Shortcode
function api_test() {
function execute_request( $args ) {
global $base_url;
$target_url = add_query_arg( $args, $base_url );
$data = wp_remote_get( $target_url );
echo '<pre><code>';
print_r( $data['body'] );
echo '<code></pre>';
}
if ( ! current_user_can( 'manage_options' ) ) die();
// API variables, please override
$base_url = 'https://website.com';
$email = 'email#gmail.com';
$product_id = '1146';
$license_key = '0g96b29x5v27fmfnmbr4hxaflky';
$instance = '';
$request = ( isset( $_GET['request'] ) ) ? $_GET['request'] : '';
$links = array(
'check' => 'Check request',
'activation' => 'Activation request',
'deactivation' => 'Deactivation',
'version_check' => 'Version Check',
);
foreach ( $links as $key => $value ) {
echo '' . $value . ' | ';
}
// Valid check request
if ( $request == 'check' ) {
$args = array(
'wc-api' => 'serial-numbers-api',
'request' => 'check',
'email' => $email,
'serial_key' => $license_key,
'product_id' => $product_id
);
echo '<br>';
echo '<br>';
echo '<b>Valid check request:</b><br />';
//execute_request( $args );
$this->execute_request($args);
}
}
add_shortcode( 'api-test', 'api_test' );
Just create execute_request() outside of shortcode.
function execute_request( $args ) {
global $base_url;
$target_url = add_query_arg( $args, $base_url );
$data = wp_remote_get( $target_url );
echo '<pre><code>';
print_r( $data['body'] );
echo '<code></pre>';
}
function api_test() {
if ( ! current_user_can( 'manage_options' ) ) die();
// API variables, please override
$base_url = 'https://website.com';
$email = 'email#gmail.com';
$product_id = '1146';
$license_key = '0g96b29x5v27fmfnmbr4hxaflky';
$instance = '';
$request = ( isset( $_GET['request'] ) ) ? $_GET['request'] : '';
$links = array(
'check' => 'Check request',
'activation' => 'Activation request',
'deactivation' => 'Deactivation',
'version_check' => 'Version Check',
);
foreach ( $links as $key => $value ) {
echo '' . $value . ' | ';
}
// Valid check request
if ( $request == 'check' ) {
$args = array(
'wc-api' => 'serial-numbers-api',
'request' => 'check',
'email' => $email,
'serial_key' => $license_key,
'product_id' => $product_id
);
echo '<br>';
echo '<br>';
echo '<b>Valid check request:</b><br />';
//execute_request( $args );
execute_request($args);
}
}
add_shortcode( 'api-test', 'api_test' );

Search Query for WooCommerce product

I have total 600 product in my website and 200 product have these type of title 'mickey' clock. When I searching product with 'mickey' clo or when search product with mikey' clo I getting search result. But when I searching mickey clo it doesn't find any products. Can you please help me to solve my problem. Following my query I using search function.
if ( ! class_exists( 'Amely_Ajax_Search' ) ) {
class Amely_Ajax_Search {
public function __construct() {
if ( class_exists( 'WpbakeryShortcodeParams' ) ) {
WpbakeryShortcodeParams::addField( 'ajax-search', array( $this, 'render' ) );
}
add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) );
// VC ajax search
add_action( 'wp_ajax_vc_ajax_search', array( $this, 'ajax_search' ) );
add_action( 'wp_ajax_nopriv_vc_ajax_search', array( $this, 'ajax_search' ) );
add_filter( 'posts_where', array( $this, 'title_like_posts_where' ), 10, 2 );
}
function ajax_search() {
$q = isset( $_GET['q'] ) ? $_GET['q'] : '';
$type = urldecode( isset( $_GET['type'] ) ? $_GET['type'] : 'post_type' );
$get = urldecode( isset( $_GET['get'] ) ? $_GET['get'] : 'post' );
$field = urldecode( isset( $_GET['field'] ) ? $_GET['field'] : 'id' );
$values = explode( ',', $get );
$post_arr = array();
if ( $type == 'post_type' ) {
$params = array(
'post_title_like' => $q,
'posts_per_page' => 10,
'post_type' => $values,
'ignore_sticky_posts' => 1,
);
$loop = new WP_Query( $params );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) {
$loop->the_post();
$post_arr[] = array(
'id' => get_the_ID(),
'name' => get_the_title(),
);
}
}
wp_reset_postdata();
} elseif ( $type == 'taxonomy' ) {
global $wpdb;
$cat_id = (int) $q;
$q = trim( $q );
$post_meta_infos = $wpdb->get_results( $wpdb->prepare( "SELECT a.term_id AS id, b.name as name, b.slug AS slug
FROM {$wpdb->term_taxonomy} AS a
INNER JOIN {$wpdb->terms} AS b ON b.term_id = a.term_id
WHERE a.taxonomy = '{$get}' AND (a.term_id = '%d' OR b.slug LIKE '%%%s%%' OR b.name LIKE '%%%s%%' )", $cat_id > 0 ? $cat_id : - 1, stripslashes( $q ), stripslashes( $q ) ), ARRAY_A );
$result = array();
if ( is_array( $post_meta_infos ) && ! empty( $post_meta_infos ) ) {
foreach ( $post_meta_infos as $value ) {
$data = array();
$data['id'] = ( $field == 'slug' ) ? $value['slug'] : $value['id'];
$data['name'] = esc_html__( 'Id', 'amely' ) . ': ' . $value['id'] . ( ( strlen( $value['name'] ) > 0 ) ? ' - ' . esc_html__( 'Name', 'amely' ) . ': ' . $value['name'] : '' ) . ( ( strlen( $value['slug'] ) > 0 ) ? ' - ' . esc_html__( 'Slug', 'amely' ) . ': ' . $value['slug'] : '' );
$result[] = $data;
}
}
}
wp_send_json( $result );
}
public function title_like_posts_where( $where, $wp_query ) {
global $wpdb;
if ( $post_title_like = $wp_query->get( 'post_title_like' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $post_title_like ) ) . '%\'';
}
return $where;
}
public function admin_scripts() {
wp_enqueue_style( 'amely-ajax-search', AMELY_THEME_URI . '/includes/vc-extend/vc-params/amely-ajax-search/token-input.css' );
wp_enqueue_script( 'amely-ajax-search', AMELY_THEME_URI . '/includes/vc-extend/vc-params/amely-ajax-search/jquery.tokeninput.min.js', array( 'jquery' ), AMELY_THEME_VERSION, true );
}
public function render( $settings, $value ) {
$param_name = isset( $settings['param_name'] ) ? $settings['param_name'] : '';
$options = isset( $settings['options'] ) ? $settings['options'] : array();
$type = isset( $options['type'] ) ? $options['type'] : 'post_type';
$get = isset( $options['get'] ) ? $options['get'] : 'post';
$field = isset( $options['field'] ) ? $options['field'] : 'id';
$ajax_limit = isset( $options['ajax_limit'] ) ? $options['ajax_limit'] : 10;
$id = uniqid( 'tokeninput-' );
$pre_populate = '';
if ( $value != '' ) {
$value_items = explode( ',', $value );
if ( $type == 'post_type' ) {
foreach ( $value_items as $value_item ) {
$value_item_info = get_post( trim( $value_item ) );
$pre_populate .= '{id: ' . $value_item_info->ID . ', name: "' . $value_item_info->post_title . '"},';
}
} elseif ( $type == 'taxonomy' ) {
foreach ( $value_items as $value_item ) {
$value_item_info = get_term_by( $field, trim( $value_item ), $get );
$pre_populate .= '{id: "' . trim( $value_item ) . '", name: "ID: ' . $value_item->term_id . ( ( strlen( $value_item_info->name ) > 0 ) ? ' - ' . esc_html__( 'Name', 'amely' ) . ': ' . $value_item_info->name : '' ) . ( strlen( $value_item_info->slug ) > 0 ? ' - ' . esc_html__( 'Slug', 'amely' ) . ': ' . $value_item_info->slug : '' ) . '"},';
}
}
}
$output = '<div class="tokeninput">';
$output .= '<input id="' . $id . '" name="' . $param_name . '" value="' . $value . '" type="text" class="wpb_vc_param_value" />';
$output .= '</div>';
$output .= '<script>jQuery("#' . $id . '").tokenInput("' . esc_js( admin_url( 'admin-ajax.php' ) ) . '?action=vc_ajax_search&type=' . urlencode( $type ) . '&get=' . urlencode( $get ) . '&field=' . urlencode( $field ) . '", {
prePopulate: [' . $pre_populate . '], resultsLimit: ' . $ajax_limit . ', excludeCurrent: true } );</script>';
return $output;
}
}
new Amely_Ajax_Search();
}

I have used return create_function in my application below. php 7.2

how to win?
PHP 7.2.0, the create_function() is deprecated.
Thanks for your help,
or wait for developers?
Edited and cleared Code
return create_function( '', "
global $chery_core_version;
$path = trailingslashit( dirname( __FILE__ ) ) . 'cherry-core.php';
$data = get_file_data( $path, array(
'version' => 'Version'
) );
if ( isset( $data['version'] ) ) {
$version = $data['version'];
}
$old_versions = null;
if ( null !== $chery_core_version ) {
$old_versions = array_keys( $chery_core_version );
}
if ( is_array( $old_versions ) && isset( $old_versions[0] ) ) {
$compare = version_compare( $old_versions[0], $version, '<' );
if ( $compare ) {
$chery_core_version = array();
$chery_core_version[ $version ] = $path;
}
} else {
$chery_core_version = array();
$chery_core_version[ $version ] = $path;
}
" );
Use anonymous functions instead:
return function () {
global $chery_core_version;
$path = trailingslashit(__DIR__) . 'cherry-core.php';
$data = get_file_data( $path, [
'version' => 'Version'
] );
if ( isset( $data['version'] ) ) {
$version = $data['version'];
}
$old_versions = null;
if ( null !== $chery_core_version ) {
$old_versions = array_keys( $chery_core_version );
}
if ( is_array( $old_versions ) && isset( $old_versions[0] ) ) {
$compare = version_compare( $old_versions[0], $version, '<' );
if ( $compare ) {
$chery_core_version = [];
$chery_core_version[ $version ] = $path;
}
} else {
$chery_core_version = [];
$chery_core_version[ $version ] = $path;
}
};

Replacing text within string that contains serialize arrays

Thanks for clicking on the question. I am trying to find and replace text within a string that contains serialize arrays. For example :
'fgm2wc_options', 'a:19:{s:15:"automatic_empty";N;s:3:"url";s:25:"http://example.com/store/";s:8:"hostname";s:9:"localhost";s:4:"port";s:4:"3306";s:8:"database";s:22:"apgadmin_store_magento";s:8:"username" ... }
I want to change http://example.com/ to smth else I can do it with str_replace but it will not change the string length indicator ( e.g s:25 ).
This is a function i am using:
function recursive_unserialize_replace( $old_url = '', $new_url = '', $data = '', $serialised = false ) {
$new_url = rtrim( $new_url, '/' );
$data = explode( ', ', $data );
try {
if ( is_string( $data ) && ( $unserialized = #unserialize( $data ) ) !== false ) {
$data = recursive_unserialize_replace( $old_url, $new_url, $unserialized, true );
} elseif ( is_array( $data ) ) {
$_tmp = array( );
foreach ( $data as $key => $value ) {
$_tmp[ $key ] = recursive_unserialize_replace( $old_url, $new_url, $value );
}
$data = $_tmp;
unset( $_tmp );
} else {
if ( is_string( $data ) ) {
$data = str_replace( $old_url, $new_url, $data );
}
}
if ( $serialised ) {
return serialize( $data );
}
} catch( Exception $error ) {
}
return $data;
}
Any ideas ?
For anyone interested this is the solution i came up with:
function unserialize_replace( $old_url = '', $new_url = '', $database_string = '' ) {
if ( substr( $old_url, -1 ) !== '/' ) {
$new_url = rtrim( $new_url, '/' );
}
$serialized_arrays = preg_match_all( "/a:\d+:.*\;\}+/", $database_string, $matches );
if( !empty( $serialized_arrays ) && is_array( $matches ) ) {
foreach ( $matches[ 0 ] as $match ) {
$unserialized = #unserialize( $match );
if ( $unserialized ) {
$buffer = str_replace( $old_url, $new_url, $unserialized );
$buffer = serialize( $buffer );
$database_string = str_replace( $match, $buffer, $database_string );
}
}
}
if ( is_string( $database_string ) ) {
$database_string = str_replace( $old_url, $new_url, $database_string );
}
return $database_string;
}
Thanks for the suggestions. Please let me know if you see anything wrong and anything i can improve

Wordpress twitter api 1.1 search class

I'm trying to use a class to made some search using the twitter api v1.1 but everytime I get and authentication error message:
This is the link to the original class: https://gist.github.com/tw2113/5468916
This is the code I'm using:
<?php
/**
* Class for connecting to Twitter's API 1.1 using WordPress APIs
*/
class TwitterAuth11 {
protected $consumer_key = 'MCQ8u3TMuBAidL4AKBtQ';
protected $consumer_secret = 'HIyZbh1FTDtpOK9qdX5yP3ZmNobnJcb2lKnhPONg6WI';
protected $access_token = '104977066-dLQj8ibcxlafcsGiwTOanw1buy0OIejhy51PzFsc';
protected $access_token_secret = 'nUkWIGX21LICgw8ZqoxwfasisB4ma3YpzwXr7EzY8';
protected $url = 'https://api.twitter.com/1.1/';
protected function authenticate( $user, $return = true ) {
$body = json_decode( $body );
if ( $body && !empty( $response['headers']['status'] ) && $response['headers']['status'] == '200 OK' ) {
if ( $return == false ) $body = null;
$noauth = '';
$badauth = 'good';
} else {
$body = null;
$badauth = 'error';
$noauth = true;
}
return array(
'response' => $body,
'badauth' => $badauth,
'noauth' => $noauth,
);
}
function get_tweets( $user = '', $count = 1 ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'screen_name' => $user, 'count' => $count ) );
$args = $this->header_args( array( 'screen_name' => $user, 'count' => $count ) );
//$this->salida = '<br> url: ' . $url . '<br>Args: ' . '<pre>'. htmlentities( print_r( $args, true ) ) .'</pre>';
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return '<strong>ERROR:</strong> '. $response->get_error_message();
$error = 'Could not access Twitter feed.';
return $this->returnData( $response, $error );
}
function search_tweets( $user = '', $count = 1, $search = '' ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'q' => urlencode( $search ) ), 'search/tweets.json' );
$args = $this->header_args( array( 'q' => urlencode( $search ) ) );
//$this->salida = '<br> url: ' . $url . '<br>Args: ' . '<pre>'. htmlentities( print_r( $args, true ) ) .'</pre>';
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return '<strong>ERROR:</strong> '. $response->get_error_message();
$error = 'Could not access Twitter feed.';
return $this->returnData( $response, $error );
}
function authenticate_user( $user = '' ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'screen_name' => $user ), 'users/lookup.json' );
$args = $this->header_args( array( 'screen_name' => $user ) );
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return false;
$error = 'Could not access Twitter user.';
return $this->returnData( $response, $error );
}
protected function returnData( $response, $error_message = '' ) {
$body = wp_remote_retrieve_body( $response );
$json = json_decode( $body );
if ( isset( $json->errors ) ) {
$errors = new WP_Error( 'twitter_auth_error', $error_message );
foreach ( $json->errors as $key => $error ) {
$errors->add( 'twitter_auth_error', '<strong>ERROR '. $error->code .':</strong> '. $error->message );
}
return $errors;
}
return $json;
}
protected function header_args( $args = array() ) {
if ( !isset( $this->user ) || ! $this->user )
return null;
// Set our oauth data
$defaults = array(
//'screen_name' => $this->user,
'oauth_consumer_key' => $this->consumer_key,
'oauth_nonce' => base64_encode( substr(md5(rand(0, 1000000)), 0, 32 ) ),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $this->access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$oauth = wp_parse_args( $defaults, $args );
//echo '<pre>'. htmlentities( print_r( $oauth, true ) ) .'</pre>';
//echo '<br><br><hr><br>';
$base_info = $this->build_base( $this->base_url(), $oauth );
$composite_key = $this->consumer_secret .'&'. $this->access_token_secret;
// create our oauth signature
$oauth['oauth_signature'] = base64_encode( hash_hmac( 'sha1', $base_info, $composite_key, true ) );
echo '<span>'.$base_info .'</span>';
echo '<br><br><hr><br>';
echo '<span>'. urldecode( $base_info ) .'</span>';
echo '<br><br><hr><br>';
$auth_args = array(
'sslverify' => false,
'headers' => array(
'Authorization' => 'OAuth '. $this->authorize_header( $oauth ),
'Expect' => false,
'Accept-Encoding' => false
),
);
return $auth_args;
}
protected function build_base( $baseURI, $params ) {
$base = array();
ksort( $params );
foreach( $params as $key => $value ){
$base[] = $key .'='. rawurlencode( $value );
}
return 'GET&'. rawurlencode( $baseURI ) .'&'. rawurlencode( implode( '&', $base ) );
}
protected function authorize_header( $oauth ) {
$header = '';
$values = array();
foreach( $oauth as $key => $value ) {
if ( $key == 'screen_name' || $key == 'count' )
continue;
$values[] = $key .'="'. rawurlencode( $value ) .'"';
}
$header .= implode( ', ', $values );
return $header;
}
protected function twAPIurl( $params = false, $trail = 'statuses/user_timeline.json' ) {
// append trailing path
$this->base_url = $this->url . $trail;
// append query args
return $params ? add_query_arg( $params, $this->base_url ) : $this->base_url;
}
protected function base_url() {
// set it up
if ( !isset( $this->base_url ) )
$this->twAPIurl();
return $this->base_url;
}
}
add_action( 'all_admin_notices', 'testing_twitter_api');
/**
* Test the api in the WordPress Dashboard
*/
function testing_twitter_api() {
echo '<div id="message" class="updated"><p>';
$twitter = new TwitterAuth11();
// Search api
$search = $twitter->search_tweets( 'ntrzacatecas', 3, '#ntr from:212Toga OR from:jasonbarkerm OR from:ntrzacatecas OR from:AlbertoChiu OR from:marcazac OR from:ortegasaul' );
// uses proper wp_error objects
if ( is_wp_error( $search ) )
echo implode( '<br/>', $search->get_error_messages( 'twitter_auth_error' ) );
else
echo '<pre>'. htmlentities( print_r( $search, true ) ) .'</pre>';
echo '</p></div>';
}
Any ideas?
Thanks for the help
Try using the Twitter API 1.1 Client for WordPress.
It's very easy to implement and all you need is your consumer_key and consumer_secret.
Example (from the README):
<?php
// Include Twitter API Client
require_once( 'class-wp-twitter-api.php' );
// Set your personal data retrieved at https://dev.twitter.com/apps
$credentials = array(
'consumer_key' => 'xxxxxxxxxxxxxxxx',
'consumer_secret' => 'xxxxxxxxxxxxxxxx'
);
// Let's instantiate Wp_Twitter_Api with your credentials
$twitter_api = new Wp_Twitter_Api( $credentials );
// Example a - Retrieve last 5 tweets from my timeline (default type statuses/user_timeline)
$query = 'count=5&include_entities=true&include_rts=true&screen_name=micc1983';
var_dump( $twitter_api->query( $query ) );

Categories