Styling WordPress's wp_link_pages() - regex

I'm using wp_link_pages() to display pagination, Which looks like:
1
2
3
4
Since this just returns a formatted html string like the above, I find it hard to wrap the current page number in a span to look something like:
<span class="current">1</span>
2
3
4
How to wrap a number surrounded with spaces (sometimes nothing or even <a> tags) in a span tag?

Put this code in functions.php
function custom_wp_link_pages( $args = '' ) {
$defaults = array(
'before' => '<p id="post-pagination">' . __( 'Pages:' ),
'after' => '</p>',`enter code here`
'text_before' => '',
'text_after' => '',
'next_or_number' => 'number',
'nextpagelink' => __( 'Next page' ),
'previouspagelink' => __( 'Previous page' ),
'pagelink' => '%',
'echo' => 1
);
$r = wp_parse_args( $args, $defaults );
$r = apply_filters( 'wp_link_pages_args', $r );
extract( $r, EXTR_SKIP );
global $page, $numpages, $multipage, $more, $pagenow;
$output = '';
if ( $multipage ) {
if ( 'number' == $next_or_number ) {
$output .= $before;
for ( $i = 1; $i < ( $numpages + 1 ); $i = $i + 1 ) {
$j = str_replace( '%', $i, $pagelink );
$output .= ' ';
if ( $i != $page || ( ( ! $more ) && ( $page == 1 ) ) )
$output .= _wp_link_page( $i );
else
$output .= '<span class="current-post-page">';
$output .= $text_before . $j . $text_after;
if ( $i != $page || ( ( ! $more ) && ( $page == 1 ) ) )
$output .= '</a>';
else
$output .= '</span>';
}
$output .= $after;
} else {
if ( $more ) {
$output .= $before;
$i = $page - 1;
if ( $i && $more ) {
$output .= _wp_link_page( $i );
$output .= $text_before . $previouspagelink . $text_after . '</a>';
}
$i = $page + 1;
if ( $i <= $numpages && $more ) {
$output .= _wp_link_page( $i );
$output .= $text_before . $nextpagelink . $text_after . '</a>';
}
$output .= $after;
}
}
}
if ( $echo )
echo $output;
return $output;
}
And call with custom_wp_link_pages()
Source: http://bavotasan.com/2012/a-better-wp_link_pages-for-wordpress/

Why regex as tag ?
You need to use something like:
Page-links in Paragraph Tags
<?php wp_link_pages('before=<p>&after=</p>&next_or_number=number&pagelink=page %'); ?>
Displays page-links wrapped in paragraph tags.
Page-links in DIV
<?php wp_link_pages('before=<div id="page-links">&after=</div>'); ?>
Displays page-links in DIV for CSS reference as <div id="page-links">.
Docs reference : http://codex.wordpress.org/Function_Reference/wp_link_pages

Related

Regex to manipulate image links

I'm using the following code snippet and regex expression to add "rel=" tags to certain affiliate links. While this code works well with text links, it doesn't work with image links that follow this format: <img src="" class=""... />
Does anyone know how to update the regex to match both text and image links?
function rewrite_affiliate_links($content) {
// Don't rewrite URLs on shop page
if ( is_page( 87422 ) ) {
return $content;
}
$content = preg_replace_callback(
'/<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
function($m) {
$Sponsored_URLS = explode(",","Amazon.com,amzn.to,shareasale.com,hsselite.7eer.net,tkqlhce.com,jdoqocy.com,dpbolvw.net,awltovhc.com,tqlkg.com,lduhtrp.net,anrdoezrs.net,ftjcfx.com,7eer.net,refersion.com,avantlink.com,/go/,www.sunstar.com.ph,www.alliedmarketresearch.com,www.theyucatantimes.com,rubikicks.com,superfoodprofiles.com,amplifi.com,performancelab.com");
$i = 0;
$j = count($Sponsored_URLS);
while ($i < $j) { ;
if ((strpos(strtolower($m[1]), strtolower($Sponsored_URLS[$i])) !== false)) {
$match = "yes";
}
$i++;
}
if ($match == "yes") {
return ''.$m[2].'*';
} else {
if ((strpos(strtolower($m[1]), $_SERVER['HTTP_HOST']) !== false) || (substr($m[1],0,1) == "#")) {
//return '<' . $m[0] . ' href="'.$m[1].'" rel="follow">'.$m[2].'</a>';
return $m[0];
} else {
return ''.$m[2].'';
}
}
},
$content);
return $content;
}
Thanks,
Michael
I'd just do it separately because you are "rendering" your "a" tag. May be like so
<?php
function rewrite_affiliate_links($content) {
$sponsoredLinks = [
"Amazon.com",
"amzn.to",
"shareasale.com",
"hsselite.7eer.net",
"tkqlhce.com",
"jdoqocy.com",
"dpbolvw.net",
"awltovhc.com",
"tqlkg.com",
"lduhtrp.net",
"anrdoezrs.net",
"ftjcfx.com",
"7eer.net",
"refersion.com",
"avantlink.com",
"\/go\/",
"www.sunstar.com.ph",
"www.alliedmarketresearch.com",
"www.theyucatantimes.com",
"rubikicks.com",
"superfoodprofiles.com",
"amplifi.com",
"performancelab.com",
];
$sponsoredLinksPrepared = implode('|', $sponsoredLinks);
$anchorRegex = "/<a.*?href=(?:\"|')(.*?(?:{$sponsoredLinksPrepared}).*?)(?:\"|').*?>(.*?)<\/a>/i";
$anchoreReplacement = '$2 *';
$imgRegex = "/<img.*?src=(?:\"|')(.*?(?:{$sponsoredLinksPrepared}).*?)(?:\"|') (.*?)>/i";
$imgReplacement = '<img src="$1" rel="sponsored noopener" $2>';
$content = preg_replace($anchorRegex, $anchoreReplacement, $content);
$content = preg_replace($imgRegex, $imgReplacement, $content);
return $content;
}
echo rewrite_affiliate_links('some');
echo "\n";
echo rewrite_affiliate_links('<img src="amzn.to/blah.jpg" width="234px" height="432px">');
echo "\n";
echo rewrite_affiliate_links('some non sponsored');
It's not a complete code it's just a general idea.

Perl Regex Extract first two section of windows path

I want to write a method to extract first two sections of windows path in Perl.
For example,
'D:\git_root_tfs\WorkStation\Projects\InterACT\Tools\server-rule-checker'
Extract as:
'D:\git_root_tfs\WorkStation'
sub Split_Location_as_VMPath {
my $location = shift;
# ^([d-z]:\\.+?\\.+?)\\
# ^(?:\\.*\\.*)\\
if($location ~~ m/^(?:\\.*\\.*)\\/){ # the path drive start from D to E;
# print "VMPath=$1\n";
# push #$vmPathList, $1;
return Convert_to_Lowercase($1);
}
return "Invalid Path $location";
}
How to write the regex?
Test case:
{
my $item = Split_Location_as_VMPath('D:\VM\ia7-BGCDev8.1\test.vhd');
my $expected = Convert_to_Lowercase('D:\VM\ia7-BGCDev8.1');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('E:\Hyper-V-2\ia-int-7.1Beta\test.vhd');
$expected = Convert_to_Lowercase('E:\Hyper-V-2\ia-int-7.1Beta');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\VM\ia7-int-7.1\test.vhd');
$expected = Convert_to_Lowercase('D:\VM\ia7-int-7.1');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\VM\ia7-int-8.1B153\test.vhd');
$expected = Convert_to_Lowercase('D:\VM\ia7-int-8.1B153');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)\test.vhd');
$expected = Convert_to_Lowercase('D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
$item = Split_Location_as_VMPath('D:\git_root_tfs\WorkStation\Projects\InterACT\Tools\server-rule-checker');
$expected = Convert_to_Lowercase('D:\git_root_tfs\WorkStation');
ok( $item eq $expected, "Test Split_Location_as_VMPath=$item");
}
Don't use a regex for file processing.
Instead use a module like File::Spec or Path::Tiny.
use strict;
use warnings;
use File::Spec;
while (<DATA>) {
my ($vol, $dir, $file) = File::Spec->splitpath($_);
my #dirs = File::Spec->splitdir($dir);
#dirs = #dirs[0..2] if #dirs > 3;
$dir = File::Spec->catdir(#dirs);
my $path = File::Spec->catpath($vol, $dir);
print "$path\n";
}
__DATA__
D:\VM\ia7-BGCDev8.1\test.vhd
E:\Hyper-V-2\ia-int-7.1Beta\test.vhd
D:\VM\ia7-int-7.1\test.vhd
D:\VM\ia7-int-8.1B153\test.vhd
D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)\test.vhd
D:\git_root_tfs\WorkStation\Projects\InterACT\Tools\server-rule-checker
Outputs:
D:\VM\ia7-BGCDev8.1
E:\Hyper-V-2\ia-int-7.1Beta
D:\VM\ia7-int-7.1
D:\VM\ia7-int-8.1B153
D:\Hyper-v\IA5-SDE-WIN2K3(Feng Tong)
D:\git_root_tfs\WorkStation
Correct regex is ^([d-z]:\.+?\.+?)\.
sub Split_Location_as_VMPath {
my $location = shift;
# ^([d-z]:\\.+?\\.+?)\\
# ^(?:\\.*\\.*)\\
if($location ~~ m/^([D-Z]:\\.+?\\.+?)\\/){ # the path drive start from D to E;
# print "VMPath=$1\n";
# push #$vmPathList, $1;
return Convert_to_Lowercase($1);
}
return "Invalid Path $location";
}
Using regex in this context is an interesting homework for students. Outside school, you should use the standard modules dedicated for this task:
use File::Spec;
sub Split_Location_as_VMPath {
my $location = shift;
my ($volume, $directories, $file) = File::Spec->splitpath($location);
my #dirs = File::Spec->splitdir($directories);
return "Invalid Path $location" unless #dirs > 2;
return lc File::Spec->catpath($volume, File::Spec->catdir(#dirs[0..2]));
}

Error occurs with while Loop PHP / MySQL NuSOAP

I have created a PHP / MySQL based web service. I wrote client.php as mentioned here
and server.php as below:
<?php
require_once("lib/nusoap.php");
$host = $_SERVER['HTTP_HOST'];
$miURL = 'http://'.$host.'/WS-Demo';
$server = new nusoap_server();
$server->configureWSDL('L3M_WebService', $miURL);
$server->wsdl->schemaTargetNamespace=$miURL;
$server->register('getDemoData',
array('fldpara' => 'xsd:Array', 'tblpara' => 'xsd:Array', 'cndpara' => 'xsd:Array'),
array('return' => 'xsd:string'),
$miURL);
function decryptRJ256($string_to_decrypt)
{
$key = 'salt_key - I';
$iv = 'salt_key - II';
$string_to_decrypt = base64_decode($string_to_decrypt);
$rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);
$rtn = rtrim($rtn, "\4");
return($rtn);
}
function encryptRJ256($string_to_encrypt)
{
$key = 'salt_key - I';
$iv = 'salt_key - II';
$rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);
$rtn = base64_encode($rtn);
return($rtn);
}
function getDemoData($flds, $tbls, $cnds){
$mysqli = new mysqli("localhost", "root", "", "test");
for($i=0;$i< count($flds); $i++) {
$flds[$i] = decryptRJ256($flds[$i]);
}
for($i=0;$i< count($tbls); $i++) {
$tbls[$i] = decryptRJ256($tbls[$i]);
}
for($i=0;$i< count($cnds); $i++) {
$cnds[$i] = decryptRJ256($cnds[$i]);
}
if(! empty($flds)) {
$what = implode(", ", $flds);
} else {
$what = "*";
}
if(! empty($tbls)) {
$from = implode(", ", $tbls);
}else {
$err = 1;
}
if(! empty($cnds)) {
$cond = " WHERE ";
$cond .= $cnds[0] . " = '" . $cnds[1] . "'";
} else {
$cond = "";
}
$sql = "SELECT ".$what." FROM ".$from . $cond;
$rsGetData = $mysqli->query($sql);
$responseData = '<?xml version="1.0" encoding="UTF-8"?>
<L3MDataSets>';
while($rowGetData = $rsGetData->fetch_assoc()) {
$responseData .= '<L3DataSet>';
foreach($rowGetData as $k => $v) {
$responseData .= '<' . $k . '>' . $v . '</' . $k . '>';
}
$responseData .= '</L3DataSet>';
}
$responseData .= '</L3MDataSets>';
$responseData = encryptRJ256($responseData);
$responseString = new soapval('return', 'xsd:string', $responseData );
return $responseData;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
From the Above code in the getDemoData function, if I remove the while loop, it gives the proper output. But when I put back the while loop it shows me output as "-Error: Response not of type text/xml: text/html" even if the SQL query is correct. I have copied and paste the generated SQL query which works in phpMyAdmin.

Cannot add role="navigation" to wp_nav_menu()

I would like my custom nav menu to have an attribute "role" with value of "navigation". It does not appear that wp_nav_menu() accepts an attributes argument. Am I missing something?
<nav role="navigation">...</nav>
Was looking for a while but then saw that you can set 'container' to false.
<nav role="navigation">
<?php
$defaults = array(
'container' => false,
'items_wrap' => '<ul>%3$s</ul>'
);
wp_nav_menu( $defaults );
?>
</nav>
Returns a simple navigation without divs in the middle.
A little late, but here is how to do it:
<?php
echo strip_tags( wp_nav_menu( array(
'echo' => false,
'items_wrap' => '<nav role="navigation">%3$s</nav>',
) ), '<a><nav>' );
?>
Here's my way to do these:
add_filter( 'wp_nav_menu', function( $nav_menu, $args ) {
if( 'primary' != $args->theme_location || 'nav' != $args->container )
return $nav_menu;
$class = $args->container_class ? ' class="' . esc_attr( $args->container_class ) . '"' : ' class="menu-'. $menu->slug .'-container"';
$id = $args->container_id ? ' id="' . esc_attr( $args->container_id ) . '"' : '';
$search = '<'. $args->container . $id . $class . '>';
$replace = '<'. $args->container . $id . $class . ' role="navigation">';
return str_replace( $search, $replace, $nav_menu );
}, 10, 2 );

How to search a substring in PHP array using regExp

$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('blah_test1','exp_test1'),
array('blah_test2','exp_test2'),
array('foo_test3','demo_test3')
)
How to get all subarray which contains foo substring with its value using php and regExp.
Expected Output:
$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('foo_test3','demo_test3')
)
You should be able to do it with
preg_grep($pattern,$array)
$input = array( /* your array */ );
$output = array();
foreach ( $input as $data ) {
$len = length($data);
for ( $i = 0; $i < $len; ++$i ) {
if ( strpos($data[$i], 'foo') > -1 ) {
$output[] = $data;
break;
}
}
}
$array = array(
array('foo_test1','demo_test1'),
array('foo_test2','demo_test2'),
array('blah_test1','exp_test1'),
array('blah_test2','exp_test2'),
array('foo_test3','demo_test3')
);
$search = 'foo';
$res = array();
foreach ($array as $arr) {
foreach ($arr as $value) {
if (preg_match('~'.preg_quote($search,'~').'~',$value)) {
// if one of the values in that array
// has the search word in it...
$res[] = $arr; break;
// push it into the $res and break
// the inner foreach loop
}
}
}
print_r($res);