hide certain category from single post - php

I need to limit number of categories display in a single post on wordpress using this script
function swift_list_cats($num){
$temp=get_the_category();
$count=count($temp);// Getting the total number of categories the post is filed in.
for($i=0;$i<$num&&$i<$count;$i++){
//Formatting our output.
$cat_string.=''.$temp[$i]->cat_name.'';
if($i!=$num-1&&$i+1<$count)
//Adding a ',' if it’s not the last category.
//You can add your own separator here.
$cat_string.=' | ';
}
echo $cat_string;
}
But I also need to hide some categories. How would I do that?

Simple answer is to return a new count not based on the length of your array so
for($i=0;$i<$num&&$i<$count;$i++){
becomes:
for($i=0;$i<10;$i++){
or use $temp = array_slice(get_the_category(), //ofset 0, //length 10);
Array slice info can be seen here.
If you need to hide some values, this would be far easier to do by adding a hidden column to your database and select values WHERE hidden = 0. However to address your question.You need to know which values you want to hide. Store these in an array and do the following.
function swift_list_cats($num){
$hiddenArray = [12, 105];
//change offset and limit to what you desire removing the slashes and labels
$temp = array_slice(get_the_category(), 0, 10);
$count=count($temp);
$cat_string = '';
for($i=0;$i<$num&&$i<$count;$i++){
if(in_array($temp[i]->cat_ID, $hiddenArray)){
continue;
}
$cat_string.=''.$temp[$i]->cat_name.'';
if($i!=$num-1&&$i+1<$count)
$cat_string.=' | ';
}
echo $cat_string;
}
$hiddenArray is the array you populate with your category IDs that you want hidden

Related

PHP - Output array value that contains a specific text marker

I'm using a function to output a collection of products in Shopify, onto a WordPress page.
I've got most of the data displaying correctly, except a custom value that is entered as a tag in Shopify. Using the api, I'm then trying to get this specific tag for the product subtitle which is formatted with att:Subtitle: before each product custom value/text.
This is the code I have got to (I've commented other unsuccessful attempts in the middle) - this is inside the overall code to show the 4 products in the Shopify collection:
// Using tags to output custom data from products
$tags = $current_product['tags'];
// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);
// Evaluate if there is a string with att:Subtitle in the product tags
// https://tecadmin.net/check-string-contains-substring-in-php/
$subtitle_attribute_key = "att:Subtitle:";
if (strpos($tags, 'att:Subtitle:') !== false) {
// Returns a numbered value corresponding to my subtitle attribute
// $key = array_search($subtitle_attribute_key, $product_tags);
$sub = strpos($tags, $subtitle_attribute_key);
// Turns the numbered value into a text value
// $numArray = explode(" ", $sub);
// var_dump($numArray);
$value = print_r($sub, true);
// $value = array_search("att:Subtitle:",$product_tabs);
// $value = array_search("att:Subtitle:", $tabs); // Warning: array_search() expects parameter 2 to be array, null given
// $result = $product_tags['$value']; // my attempt to return the text
// Remove att:Subtittle: in front of the subtitle value to output the clean final value
$subtitle = ltrim($value, 'att:Subtitle:');
}
So far it comes out as a number value where I'm displaying $subtitle... but I can't figure out how to display the custom text value instead.
Any ideas?
Thanks
EDIT: I am working with products that have multiple tags and I do not control these. Out of the tags I'm trying to find the one that starts with att:Subtitle: but only show the custom value after that marker.
When I echo $tags, the ist comes out something like this:
att:Benefit:balance, att:Perfect:Combination Skin, att:Size: 1.8 oz, att:Subtitle: Multi-Tasking Product, Key Ingredient 1, Key Ingredient 2, Essentials, meta-related-product-xyz, meta-related-product-brandname
They will all have a different list of tags
Of course it comes out as a number. You're getting a number from the strpos() and ultimate trying to run ltrim() on it.
If you're expecting the desired text to be in $tags immediately following 'att:Subtitle:' and have nothing else in that string, $subtitle = substr($tags, strpos('att:Subtitle:') + strlen('att:Subtitle:')); should give it to you. If you're expecting it to possibly be an element in the $product_tags array, need to loop (I'm assuming it shows up once, at most):
foreach ($product_tags as $product_tag) {
if (strpos($product_tag, 'att:Subtitle:') !== false) {
$subtitle = substr($product_tag, strpos($product_tag, 'att:Subtitle:') + strlen('att:Subtitle:'));
break;
}
}
So for what I understand you're trying to get rid of 'att:Subtitle:' from the tags on your products descriptions? maybe you should try replacing that value on your tags array
// Using tags to output custom data from products
$tags = $current_product['tags'];
// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);
// Get rid of attribute on product tag
for($i = 0; $i < count($product_tags); $i++){
$subtitle = str_replace(':att:Subtitle','',$product_tags[i]);
}

Woocommerce Order / AFC get_sub_field / get_sub_field_object (array)

Have setup ACF repeater field that stores various amount of tracking numbers in the order. Having 0 success with retrieving this information so need some advice.
Am using this to put information in subfields and it does the job
foreach ($base->DocumentLines->DocumentLine as $item) {
foreach ($item->MiscData as $misc) {
foreach ($misc->PackageNo as $package) {
$trackno = (string)$package->TrackingNo;
update_post_meta("$order_id", $field_rep, $count);
$sub = $count +1;
update_sub_field(array($field_key_rep, $sub, $field_key_sub), $trackno, "$order_id");
$count = $count + 1;
update_field($field_key, $trackno, "$order_id");
}
}
}
This works well, but then i need to retrieve this numbers and write em out. They are getting included in an email so need to retrieve the data outside of order.
Before rebuilding the function to be able to handle multiple numbers i did use a single field and could retrieve the information with
get_post_meta($order_id, 'tracking', true);
Feels like i have been trying everything now but got absolutely nothing.
Image from one of the orders, in this one it’s 10 tracking numbers but it varies from 1 to 20 if it's to any help.
The feeling when you realize after 10 hours that your missed a capital letter in sub field name.
Just wanted to submit my solution and hopefully it can help someone else having issues with ACF Repeater fields + Woocommerce
For my specific case i did make a function that could extract all the tracking numbers my function above did add from XML files.
$function trackingNo($postID) {
$field_rep = 'trackingNo';
$field_sub = 'no';
if (have_rows($field_rep, $postID)) {
$trackingNo = array();
// loop through the rows of data
while (have_rows($field_rep, $postID)):
the_row();
// Add to array
$trackingNo[] = get_sub_field($field_sub);
endwhile;
$foo = implode('&consignmentId=', $trackingNo);
$bar = 'urlzz/tracktrace/TrackConsignments_do.jsp?&consignmentId=';
$value = $bar . $foo;
return $value;
}
}
Any advice for improvement is always welcome, my PHP is so'n'so :)

String from an array from an array from the database

Okay so, first of all, I searched through the www for this question, and I found some question related to arrays but not exactly to mine.
Okay so as you may know, paypal only allows one custom variable to be $POST but I need to gather the product id AND the quantity of the item bought. So to do this I made my custom variable into something that would get the post like (25-1,12-3,13-4) it means, the user bought 3 items(separated by commas), where the first number is the product id (then the separator '-' comes in) and the second one is the quantity. (so they're all in the same row and column)
Now my problem is displaying it from the database. I need to get the product name and details that's why I need to separate the numbers from each array as a string and fetch the data from the database for the information of the product. (I'm using an older version of php anyway, 5.2, I guess.)Now the problem is:
1.) It returns the word 'Array' (literally) so it would say like ArrayArrayArray
2.) How do I explode/separate those data so I can get it because I need the product ID to fetch some other data... I tried exploding it into array, then exploding it again but doesn't work (most likely my code is wrong?)
Here is my code: (I've already connected to the database)
$data = mysql_query("SELECT * from transactions") or die(mysql_error());
/* My table tag and headers goes here */
while($info = mysql_fetch_array( $data )) {
echo "<tr>";
echo '<td>' . $info['id'] . '</td>';
echo "<td>";
$array = $info['product_id_array'];
$explode_array = explode(",", $array);
foreach($explode_array as $explode_more){
$explode_more = explode("-", $explode_array);
$prod_id = $explode_more[0];
$quantity = $explode_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
echo"</td>";
echo"<tr>";
}
If only paypal would allow multiple custom variables T_T Thank you guys. Forgive me if I can't express my question very well or my language is not good, as english is not my first language :), Good day!
Your variable names are mixed up. Inside the foreach-loop, you should do something like this
foreach($explode_array as $explode_more){
$explode_even_more = explode("-", $explode_more);
$prod_id = $explode_even_more[0];
$quantity = $explode_even_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
Note, that $explode_more is used inside the loop and $explore_array is left as is.
Separate this in multiple tables, never store non-atomic values in 1 column.
Certainly not when they have relation with another table.
Suppose you want to know the sales from a certain product in some period.

Grab Lists from Database then Grab Top Tags In Each List

So, let's say I have a database where users can add "tags" that PHP turns into a comma separated list. The user puts in 'Orange, Peppers, Biscuits Onions Grapes' and It turns into 'orange,peppers,biscuits,onions,grapes'. Now, I'm pretty sure that will be easy enough, and I don't need help there. But now these "tags" are listed in the SQL Database.
$individuallist = $databaserow['database_list'];
$arrayoflist = explode(',', $individuallist );
foreach($arrayoflist as $individualtag) {
//Display Tags
}
So, good, I can grab these tags and use them for the specific item they relate to and I can take the list and turn it into an array and foreach them to display each individual one.
However, I need to take all the lists in the database and add them together. For example:
while($databaserow = mysql_fetch_assoc($databaseresult)) {
$database_array[] = $databaserow ['database_list'];
}
So these two example lists will be combined into an array
// The Two Lists
// 'orange,peppers,biscuits,onions,grapes'
// 'peppers,orange,market,turkey,juice'
$database_full_list = implode(',', $database_array);
// The Full List
// 'orange,peppers,biscuits,onions,grapes,peppers,orange,market,turkey,juice'
Now that I have the full list of tags, I need to count to see which Tags are the Top 30. The idea is that as more tags are added to the database, the Top 30 Tags would be listed in order of how many there are of them.
Orange (2)
Peppers (2)
Bisquits (1)
Market (1)
etc.
I don't know how to this part of the coding.
$split_tags = explode(',', $database_full_list);
$count_tags = array();
foreach($split_tags as $tag) {
if(!array_key_exists($tag, $count_tags))
$count_tags[$tag] = 0;
$count_tags[$tag]++;
}
asort($count_tags);
foreach(array_reverse($count_tags) as $tag => $count)
echo "$tag ($count)<br/>";

php - build array out of computations from multidimensional array

This is driving me nuts.
I'm attempting to reada CSV file (done) and then work through the permutations of each row.
Each row contains several bits of data (name, price etc.).
Some of them contain slash separated lists (a/b/c/c3/c65).
What I need to do is generate all the possible variations of each row.
Example:
Row 12 =
Name = name,
Price = price,
Models = x12/x14/x56,
Codes = LP1/LP12/LP899/XP90/XP92,
From that I should be able to generate 15 variations, each with the same Name and Price, but with different Codes and varied Models;
Name Price X12 LP1
Name Price X12 LP12
Name Price X12 LP899
~
Name Price X56 XP90
Name Price X56 XP92
Yet I'm either overwriting pre-existing versions, or generating individual versions, but only getting 1 set of values changing (so I may get the 15 versions, but only Model changes, everything else stays the same).
Any help/thoughts or pointers would be appreciated!
So you have one row containing that much items,
say
$row = array('Name'=>'name', 'price'=>'price','models'=>'x12/x14/x56','codes'=>'LP1/LP12/LP899/XP90/XP92')
and you want to split models and codes with "/" then have each item as a new row in the array with all the columns those having the same value for price and name field, here is how you can do this,
$line = 0;
$result_array = array();
$result_array[$line]['name'] = $row['name'];
$result_array[$line]['price'] = $row['price'];
//split the models using explode
$tmpModels = explode("/",$row['models']);
foreach($tmpModels as $mod){
if($line > 0){
$result_array[$line]['name'] = $row['name'];
$result_array[$line]['price'] = $row['price'];
}
$result_array[$line]['model'] = $mod;
$line++;
}
$line = 0;
//now split the codes using explode
$tmpCodes = explode("/",$row['models']);
foreach($tmpCodes as $cod){
$result_array[$line]['code'] = $cod;
$line++;
}
if(count($tmpCodes) > count($tmpModels)){ // then few more rows should be added to include all from codes
foreach($tmpCodes as $cod){
$result_array[$line]['name'] = $row['name'];
$result_array[$line]['price'] = $row['price]'
$result_array[$line]['model'] = '';
$result_array[$line]['code'] = $cod;
$line++;
}
}
$result_array will have what you want.
This code is not tested, so there can be some errors, btw i hope this will surely give you an idea on how to achieve that.
Let's say you have array that looks like this:
$variant=Array();
$list[0]=array('Name'=>'Item name', 'Price'=>'$400','Models'=>'x12/x14/x56','Codes'=>'LP1/LP12/LP899/XP90/XP92');
$list[1]=array('Name'=>'Item name', 'Price'=>'$400','Models'=>'x12/x14/x56','Codes'=>'LP1/LP12/LP899/XP90/XP92'); // and more array.......
for($i=0;$i<count($list);$i++){
$Names=$list[$i]["Name"];
$Prices=$list[$i]["Price"];
$Models=explode("/",$list[$i]["Models"]);
$Codes=explode("/",$list[$i]["Codes"]);
for($i2=0;$i2<count($Codes);$i2++){
$variant[]=Array("name"=>$Names,"price"=>$Prices,"model"=>$Models[0],"code"=>$Codes[$i2]);
$variant[]=Array("name"=>$Names,"price"=>$Prices,"model"=>$Models[1],"code"=>$Codes[$i2]);
$variant[]=Array("name"=>$Names,"price"=>$Prices,"model"=>$Models[2],"code"=>$Codes[$i2]);
// You can add more models by copy paste it and change $Models[2] with next available $Models array index
}
}
var_dump($variant);
?>
The results will produce 30 array, because we have 2 rows, so that's not wrong ... okay
Reason for looping the codes
Because codes is more greater than models. So, we can catch all values.
Good luck, btw i have test it and that's worked

Categories