Confused with If then else complex condition - php

I' am creating a menu using array. I' am currently stuck at the point where am confused how to show all children of the menu. Below is the code:
<ul class="nav navbar-nav">
<?php
$get_admin_menu = get_admin_menu();
$get_admin_submenu = get_admin_submenu();
foreach( $get_admin_menu as $menu ){
$mi = 1;
$menu_title = $menu["title"];
$menu_slug = $menu["slug"];
$menu_url = $menu["url"];
echo "<li class=\"dropdown\">";
echo "<a href=\"$menu_url\">";
echo $menu_title;
echo "</a>";
$si = 0;
$total = count($get_admin_submenu);
foreach( $get_admin_submenu as $menu ){
$mi++;
$submenu_title = $menu["title"];
$submenu_slug = $menu["slug"];
$submenu_parent = $menu["parent"];
if( $menu_url == $submenu_parent ){
$si++;
if( $si == 1 ){ echo "<ul class=\"dropdown-menu\" role=\"menu\">"; }
echo "<li>";
echo "<a href=\"$submenu_parent?page=$submenu_slug\">";
echo $submenu_title;
echo "</a>";
echo "</li>";
}
if( $si == 1 ){ echo "</ul>"; break; }
}
echo "</li>";
}
?>
</ul>
**The above code renders **
The outcome of this code should be
This is the code, how the menu and submenu are catered into the array
/* Add Administrator Menu */
$add_admin_menu = array();
function add_admin_menu( $args ) {
global $add_admin_menu;
return $add_admin_menu[] = $args;
}
/* Get Administrator Menu */
function get_admin_menu(){
global $add_admin_menu;
return $add_admin_menu;
}
/* Add Administrator Submenu */
$add_admin_submenu = array();
function add_admin_submenu( $args ) {
global $add_admin_submenu;
return $add_admin_submenu[] = $args;
}
/* Get Administrator Submenu */
function get_admin_submenu(){
global $add_admin_submenu;
return $add_admin_submenu;
}
function recursive_array_search($needle, $haystack) {
foreach($haystack as $key => $value){
$current_key = $key;
if($needle === $value or (is_array($value) and recursive_array_search($needle,$value) !== false)) {
echo $current_key;
}
}
}
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return false;
}
$args = array(
"title" => "Dashboard",
"slug" => "dashboard",
"url" => "dashboard.php"
);
add_admin_menu($args);
$args = array(
"title" => "Media",
"slug" => "media",
"url" => "media.php"
);
add_admin_menu($args);
$args = array(
"title" => "Manage Pages",
"slug" => "pages",
"url" => "pages.php"
);
add_admin_menu($args);
$args = array(
"title" => "Plugin",
"slug" => "plugin",
"url" => "plugin.php"
);
add_admin_menu($args);
$args = array(
"title" => "Users",
"slug" => "users",
"url" => "users.php"
);
add_admin_menu($args);
$args = array(
"title" => "Tools",
"slug" => "tools",
"url" => "tools.php"
);
add_admin_menu($args);
$args = array(
"title" => "Settings",
"slug" => "settings",
"url" => "settings.php"
);
add_admin_menu($args);
/* Media */
$args = array(
"title" => "Media Manager",
"slug" => "media-manager",
"parent" => "media.php"
);
add_admin_submenu($args);
$args = array(
"title" => "Media Settings",
"slug" => "media-settings",
"parent" => "media.php"
);
add_admin_submenu($args);
/* Pages */
$args = array(
"title" => "View All",
"slug" => "view-all",
"parent" => "pages.php"
);
add_admin_submenu($args);
$args = array(
"title" => "Add New",
"slug" => "add-new",
"parent" => "pages.php"
);
add_admin_submenu($args);
$args = array(
"title" => "Template Manager",
"slug" => "template",
"parent" => "pages.php"
);
add_admin_submenu($args);
/* Settings */
$args = array(
"title" => "General",
"slug" => "general",
"parent" => "settings.php"
);
add_admin_submenu($args);
$args = array(
"title" => "Mail Server",
"slug" => "mail-server",
"parent" => "settings.php"
);
add_admin_submenu($args);
$args = array(
"title" => "Security",
"slug" => "security",
"parent" => "settings.php"
);
add_admin_submenu($args);

You break the loop after first menu sub-element. At the end of the loop you have:
if( $si == 1 ) { echo "</ul>"; break; }
Try this one here:
if( $si >= ($total - 1) ) { echo "</ul>"; break; }

Related

WooCommerce - Get product variation SKU in loop

I'm trying to get the product variation SKU's but it always returns blank. I've tried everything I can think of so far and I have been unable to find any answer here.
foreach ($available_variations as $variation) {
$variation_id = $variation->ID;
$variant = new WC_Product_Variation($variation_id);
// Get data from the product variation
$excerpt_var = wpautop($variation['variation_description']);
$sku = $variation['sku'];
$price = $variation['display_regular_price'];
$price = number_format($price, 0, ',', ' ');
if ($price != null) {
$price = $price . ",-";
}
$results[] = array(
"id" => $available_variations,
"cat" => $cat->name,
"sku" => $sku,
"title" => $title,
"price" => $price != null ? $price : "",
"excerpt" => $excerpt_var,
"thumbnail" => $thumbnail,
"type" => "variation"
);
}
Whole function to get all prods and variations is here:
function get_all_prods_for_csv() {
$results = array(); // Rows to be returned
// Settings
$taxonomy = 'product_cat';
$title = '';
$empty = 0;
// Query arguments
$args_cat = array(
'taxonomy' => $taxonomy,
'orderby' => 'menu_order',
'show_count' => 0, // 1 for yes, 0 for no
'pad_counts' => 0, // 1 for yes, 0 for no
'hierarchical' => 0, // 1 for yes, 0 for no
'title_li' => $title,
'hide_empty' => $empty
);
// For all categories
foreach (get_categories( $args_cat ) as $cat) {
// If root category
if ($cat->category_parent === 0) {
$category_id = $cat->term_id;
$category_slug = $cat->slug;
$cat_thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$cat_image = wp_get_attachment_url( $cat_thumbnail_id );
$results[] = array(
"id" => $category_id,
"cat" => $cat->name,
"sku" => '',
"title" => '',
"price" => '',
"excerpt" => category_description( $category_id ),
"thumbnail" => $thumbnail,
"type" => "category"
);
// Get all products for current category
// Query arguments
$args_prod = array(
'post_type' => 'product',
'posts_per_page' => -1,
'order' => 'asc',
'orderby' => 'menu_order',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $category_id
)
)
);
$products = get_posts( $args_prod );
// For all products
foreach ( $products as $prod ) {
$product = wc_get_product($prod->ID);
// Get data from the product
$title = $product->get_title();
$thumbnail = get_the_post_thumbnail_url($prod->ID);
$excerpt = wpautop($product->get_short_description()); // wpautop(get_the_excerpt($prod->ID));
// If single variation
if( $product->is_type( 'simple' ) ) {
$price = $product->get_price();
$price = number_format($price, 0, ',', ' ');
$results[] = array(
"id" => $prod->ID,
"cat" => $cat->name,
"sku" => $product->get_sku(),
"title" => $title,
"price" => $price != null ? $price . "" : "",
"excerpt" => $excerpt,
"thumbnail" => $thumbnail,
"type" => "simple"
);
} else if ( $product->is_type( 'variable' ) ) {
$available_variations = $product->get_available_variations();
$counting_variations = 1;
foreach ($available_variations as $variation) {
$counting_variations++;
}
$results[] = array(
"id" => $prod->ID,
"cat" => $cat->name,
"sku" => "",
"title" => $title,
"price" => "",
"excerpt" => $excerpt,
"thumbnail" => $thumbnail,
"type" => "variation_root"
);
foreach ($available_variations as $variation) {
$variation_id = $variation->ID;
$variant = new WC_Product_Variation($variation_id);
// Get data from the product variation
$excerpt_var = wpautop($variation['variation_description']);
$sku = $variation['sku'];
$price = $variation['display_regular_price'];
$price = number_format($price, 0, ',', ' ');
if ($price != null) {
$price = $price . ",-";
}
$results[] = array(
"id" => $available_variations,
"cat" => $cat->name,
"sku" => $sku,
"title" => $title,
"price" => $price != null ? $price : "",
"excerpt" => $excerpt_var,
"thumbnail" => $thumbnail,
"type" => "variation"
);
}
}
}
}
}
return $results;
}
This line
$sku = $variation['sku'];
should be
$sku = $variant['sku'];
since you get the object as that variable $variant.

WordPress – output categories, posts and images to JSON

I'm trying to recreate a JSON file with a specific structure and only getting so far as I'm not that familiar with PHP.
I'd like to list all used/non-empty categories, then all posts within each category and then all images/other details used in each post.
I'm not sure how the code should look in the loop. I'd need the JSON to be exactly like below (brackets) as I'm feeding it to a D3 script:
{
"project": "Farm", // website name
"about": "What we have on the farm.",
"categories": [ //post categories
{
"slug": "fruits",
"title": "Fruits",
"description": "All about fruits.",
"posts": [ // all posts within a category
{
"slug": "apples",
"title": "Apples",
"excerpt": "Apple trees and fruits.",
"tags": "tree, apple",
"post_images": [
{
"id": 25,
"title": "Apple trees.",
"filename": "apple-trees.jpg",
"desc": "Rows of apple trees.",
"tags": ""
},
(...)
The PHP script so far (in functions.php):
function export_to_json() {
global $post;
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$posts = array();
$cats = get_categories( $cat_args );
foreach( $cats as $cat ) {
$query = new WP_Query( $post_args );
while ( $query->have_posts() ): $query->the_post();
$posts[] = array(
'categories' => [
'title' => $cat->cat_name,
'description' => $cat->description,
'posts' => [
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'images' => get_attached_media( 'image' ),
'tags' => get_tags()
]
]
);
endwhile;
wp_reset_query();
}
$data = json_encode($posts, JSON_PRETTY_PRINT);
$upload_dir = wp_get_upload_dir();
$file_name = date('Y-m-d') . '.json';
$save_path = $upload_dir['basedir'] . '/' . $file_name;
$f = fopen($save_path, "w");
fwrite($f, $data);
fclose($f);
}
add_action('save_post', 'export_to_json');
The script is wrong because categories get repeated for each post and I'd like all posts within a category to be properly nested.
Any help with this would be much appreciated. Thanks.
Here you go:
function export_to_json() {
global $post;
$categories = array();
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories( $cat_args );
foreach( $cats as $cat ) {
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'category__in' => $cat->term_id
);
$get_posts = array();
$posts = get_posts( $post_args );
foreach($posts as $post){
$tags = get_the_tags($post->ID);
$i = 0;
$tag_names = '';
$post_images = array();
if( $tags) {
foreach( $tags as $tag ) { $i++;
$comma = $i == count($tags) ? '' : ', ';
$tag_names .= $tag->name . $comma;
}
}
$images = get_post_gallery($post->ID, false);
if($images){
$image_ids = explode(",", $images['ids']);
foreach ($image_ids as $image ){
$img = wp_prepare_attachment_for_js($image);
$post_images[] = array(
"id" => $img['id'],
"title" => $img['name'],
"filename" => $img['filename'],
"desc" => $img['description'], //Pulls the image description
'tags' => $tag_names
);
}
}
$get_posts[] = array(
'slug' => $post->post_name,
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'tags' => $tag_names,
'post_images' => $post_images
);
}
$categories[] = array(
'slug' => $cat->slug,
'title' => $cat->cat_name,
'description' => $cat->description,
'posts' => $get_posts
);
}
$output = array(
'project' => get_bloginfo('name'),
'about' => get_bloginfo('description'),
'categories' => $categories
);
$data = json_encode($output, JSON_PRETTY_PRINT);
}

Storing multiple values in array and output csv

I am trying to setup a CSV feed for another marketplace.
Problem is that only one set of values are stored to the array.
$data = array();
while ($loop->have_posts()) : $loop->the_post();
$product = get_product($loop->post);
$title = $product->get_title();
$link = get_permalink();
$description = strip_tags($post->post_content);
$details = $post->the_excerpt;
$categories = get_the_terms($post->ID, 'product_cat');
$sku = $product->get_sku();
$price = $product->price;
$imageinfo = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID));
$imageurl = $imageinfo[0];
$image = preg_replace($suchmuster, '', $imageurl);
foreach ($categories as $c) {
$category = $c->name;
}
$data += [
"ean" => $sku,
"condition" => "100",
"listing_price" => $price,
"minimum_price" => $price,
"amount" => 9,
"delivery_time" => "b",
"location" => "DE"
];
endwhile;
wp_reset_query();
echo '<pre>';
print_r($data);
echo '</pre>';
My Array now looks like this:
Array
(
[ean] => SportsBag16
[condition] => 100
[listing_price] => 39
[minimum_price] => 39
[amount] => 9
[delivery_time] => b
[location] => DE
)
But there should be way more entries(22).
What am i doing wrong? Thanks for any help.
You are append the output to string , you have to make the array in while conditions, in your code it replace the previous value with new values.
$data = array();
while ($loop->have_posts()) : $loop->the_post();
$product = get_product($loop->post);
$title = $product->get_title();
$link = get_permalink();
$description = strip_tags($post->post_content);
$details = $post->the_excerpt;
$categories = get_the_terms($post->ID, 'product_cat');
$sku = $product->get_sku();
$price = $product->price;
$imageinfo = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID));
$imageurl = $imageinfo[0];
$image = preg_replace($suchmuster, '', $imageurl);
foreach ($categories as $c) {
$category = $c->name;
}
$array1 = array(
"ean" => $sku,
"condition" => "100",
"listing_price" => $price,
"minimum_price" => $price,
"amount" => 9,
"delivery_time" => "b",
"location" => "DE"
);
$data []= $array1;
endwhile;
wp_reset_query();
echo '<pre>';
print_r($data);
echo '</pre>';
Your error lies in using += to append to the array. Use the following instead:
$data[] = [
"ean" => $sku,
"condition" => "100",
"listing_price" => $price,
"minimum_price" => $price,
"amount" => 9,
"delivery_time" => "b",
"location" => "DE"
];

php create json multiple arrays

php create json multiple arrays. Following code with php i need output like that json .. so many array and object confusing me. we using wordpres
<?php
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0
));
foreach ( $categories as $category ) {
$category_id = $category->term_id;
$category_name = $category->name;
echo $category_name;
echo "<br>";
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category' => $category_id
);
$myposts = get_posts( $args );
foreach( $myposts as $post ){
$category_postname = $post->post_title;
echo $category_postname;
echo "<br>";
}
}
?>
Php output is"
Testcat1
pos1
post2
Testcat2
post3
post4
TestCat3
post5
post 6
I need create Json like this:
{
"data": [
{
"cat": "Testcat1",
"post": [
{
"name": "post1"
},
{
"name": "post2"
}
]
},
{
"cat": "Testcat2",
"post": [
{
"name": "post3"
},
{
"name": "post4"
}
]
},
{
"cat": "Testcat3",
"post": [
{
"name": "post5"
},
{
"name": "post6"
}
]
}
]
}
i need like this json output.
You should put everything in an array and the json_encode it. I commented out your echos, so you could use them if you need later.
<?php
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0
));
// init empty array with root "data"
$array = array( 'data' => array() );
// set counter to 0 for array later on
$n = 0;
foreach ( $categories as $category ) {
$category_id = $category->term_id;
$category_name = $category->name;
// store cat.name
$array['data'][$n]['cat'] = $category_name;
// echo $category_name;
// echo "<br>";
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category' => $category_id
);
$myposts = get_posts( $args );
// init posts counter
$i = 0;
foreach( $myposts as $post ){
$category_postname = $post->post_title;
$array['data'][$n]['post'][$i]['name'] = $category_postname;
$array['data'][$n]['post'][$i]['id'] = $post->ID;
// echo $category_postname;
// echo "<br>";
// increment post loop counter
$i++;
}
// increment counter for array
$n++;
}
echo json_encode( $array );
?>

Adding multiple values in attribute

So here is shortcode that i can use to output names based on attributes.
For example, [my_site dfd_name="boy"] will output all boys name.
However if I put "girl" in the name attribute, it does not recognize it. ([my_site dfd_name="boy,girl"]).
Here is the full php:
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
function sp_shortcode_listings($atts, $content = null, $code = "") {
global $wp_query;
global $title;
global $active_tab;
global $showposts;
global $sp_taxonomy;
$defaults = array(
'type' => 'grid',
'before' => '',
'after' => '',
'wrap' => 'div',
'title' => '',
'showposts' => '12',
'type'=> 'grid',
);
extract( shortcode_atts( $defaults, $atts ) );
if ($showposts == 12) {
$showposts = isset($_GET['showposts']) ? $_GET['showposts'] : '12';
}
$shorcode = "sc";
if(!empty($atts))
{
foreach ( $atts as $key => $val)
{
if(strstr($key, 'dfd'))
{
$metaquery[] = array(
'key' => $key,
'value' => $val,
'compare' => 'LIKE',
'terms' => explode(',',$val)
);
}
}
}
if(empty($metaquery))
{
$shorcode = "";
}
global $active_tab;
$active_tab = isset( $_GET[ 'type' ] ) ? $_GET[ 'type' ] : $type;
include(my_site_dir . '/archive-filter.php');
global $post;
ob_start();
if ( have_posts() )
{
my_template_property_archive_content_main_shortcode();
}
else
{
echo apply_filters( 'my_site_no_match', 'Sorry, no name matched your criteria' ) ;
}
$output_string = ob_get_contents();
ob_end_clean();
$output = sprintf( '<%4$s class="sp">%1$s%3$s%2$s</%4$s>', $before, $after, $output_string, $wrap );
wp_reset_query();
return $output;
}
add_shortcode("my-listings", "sp_shortcode_listings");
?>
How can I change it so that I can add multiple values in the "dfd" attributes?
Thanks

Categories