Add shortcode to TinyMCE for show menu dropdown - php

I have a shortcode for show menu:
//menu categories shortcode
function menu_categories_shortcode( $atts, $content = null ){
extract( shortcode_atts( array(
'menu' => ''
), $atts ) );
ob_start();
wp_nav_menu(array(
'menu' => $menu,
'container' => 'ul',
'container_class' => 'sidebar-categories',
'items_wrap' => '%3$s',
'depth' => 1
));
$content = ob_get_contents();
ob_end_clean();
return $content;
}
add_shortcode('menu-categories', 'menu_categories_shortcode');
Now, i wanna add shortcode button of menu shortcode to TinyMCE for client can choose menu they want to show.
Ex: On Home page, client want to show menu with menu name is Menu 1, so shortcode will be: [menu-categories menu="Menu 1"]
When client click menu shortcode button, a dropdown of all menu will be popup for client can choose menu they want.
This is my js to call menu popup:
(function() {
tinymce.create('tinymce.plugins.menuPlugin', {
init: function(ed, url) {
// Register commands
ed.addCommand('mcebutton', function() {
ed.windowManager.open({
file: url + '/menu_popup.php',
width: 220 + parseInt(ed.getLang('button.delta_width', 0)),
height: 240 + parseInt(ed.getLang('button.delta_height', 0)),
inline: 1
}, {
plugin_url: url
});
});
// Register buttons
ed.addButton('menu_button', {
title: 'Choose Menu',
cmd: 'mcebutton',
image: url + '/icon.gif'
});
},
});
tinymce.PluginManager.add('menu_button', tinymce.plugins.buttonPlugin);
})();
The problem I've in menu_popup.php, how to i get all menus?
My menu_popup.php file:
<form action="/" method="get" accept-charset="utf-8">
<div>
<label for="button-url">Choose Menu</label>
<?php $menus = get_registered_nav_menus();
if($menus) : ?>
<select id="button-url">
<?php
foreach ($menus as $key => $menu) : ?>
<option value="<?php echo $menu; ?>"><?php echo $menu; ?></option> <?php endforeach; ?>
</select>
<?php endif; ?>
</div>
<div>
Insert
</div>
</form>
Error i have:
Thanks so much!!!

In your menu_poup.php you need to include this code:
define('WP_USE_THEMES', false);
require('../../../wp-blog-header.php');
https://codex.wordpress.org/Integrating_WordPress_with_Your_Website
to access WordPress functions. I just tried it using your code and it worked.

Related

wordpress mega menu items, iterating all items on each level of a menu tree (dropdowns)

I've been re-writing a portion of this mega menu code to better serve menus where we have 3 levels of items. In this case the main menu has a dropdown called "Sports" which then has "basketball" and "football" each of which are dropdowns with their own respective teams so the menu tree looks like this:
-sports
--basketball
---commanders
---chargers
--football
---sharks
---bears
The issue is that this "sports" dropdown then shows everything in a single list and I want to display a column for each sport. My problem lies in the loop where I'm getting li elements because it iterates one by one and gives the football and basketball options the has-children class, which is fine, but I want to iterate on all 2nd level items first (i.e. the football and basketball items) so that I can make those into columns and then just use CSS for the rest.
How can I restructure the list items in order to achieve that properlY?
<?php
/**
* Mega Menu Category - Display recent posts from a parent category.
*/
// Walker to create the left part of mega menu
$sub_walker = new Walker_Nav_Menu;
$have_sub_menu = !empty($sub_items) ? true : false;
if (!isset($sub_items)) {
$sub_items = array();
}
?>
<div class="sub-menu mega-menu mega-menu-a wrap">
<?php if ($have_sub_menu): ?>
<div class="column sub-cats">
<ol class="sub-nav">
<?php foreach ($sub_items as $nav_item): ?>
<?php
ob_start();
// Simulate a simpler walk - $escaped_output is passed-by-ref
$escaped_output = '';
$sub_walker->start_el($escaped_output, $nav_item, 0, $args);
$sub_walker->end_el($escaped_output, $nav_item, $args);
ob_end_clean();
echo $escaped_output; // phpcs:ignore WordPress.Security.EscapeOutput -- Safe markup generated via WordPress default Walker_Nav_Menu::start_el()
?>
<?php endforeach; ?>
<li class="menu-item view-all menu-cat-<?php echo esc_attr($item->object_id); ?>"><a href="<?php echo esc_url($item->url); ?>"><?php
esc_html_e('View All', 'bunyad'); ?></a></li>
</ol>
</div>
<?php endif; ?>
<?php
// Add main item (view all) as default
array_push($sub_items, $item);
$columns = $have_sub_menu ? 4 : 5;
?>
<section class="column recent-posts" data-columns="<?php echo intval($columns); ?>">
<?php foreach ($sub_items as $item): ?>
<div class="posts" data-id="<?php echo esc_attr($item->object_id); ?>">
<?php
echo Bunyad::blocks()->load(
'Loops\Grid',
[
'query_type' => 'custom',
'posts' => $columns,
'cat' => $item->object_id,
'columns' => $columns,
'meta_items_default' => false,
'meta_above' => [],
'meta_below' => ['date'],
'heading_type' => 'none',
'excerpts' => false,
'style' => 'sm',
'space_below' => 'none',
'pagination' => false,
'cat_labels' => false
]
);
?>
</div> <!-- .posts -->
<?php endforeach; ?>
</section>
</div>

ACF custom block get_field() shows null on front-end?

I built a custom block using ACF acf_register_block_type(); function
it works fine in the WordPress dashboard (block editor), it shows the field data and all good..
but in the front-end (view page) the fields are NULL
any help on how to display field data in the front-end??
functions.php code:
add_action('acf/init', 'my_acf_init_block_types');
function my_acf_init_block_types()
{
// Check function exists.
if (function_exists('acf_register_block_type')) {
// register a hero block.
acf_register_block_type(array(
'name' => 'banner',
'title' => __('Banner'),
'description' => __('A custom hero block.'),
'render_callback' => 'my_acf_block_render_callback',
'category' => 'home-sections',
'icon' => 'cover-image',
'keywords' => array('basic', 'banner')
));
}
}
function my_acf_block_render_callback($block)
{
// convert name ("acf/hero") into path friendly slug ("hero")
$slug = str_replace('acf/', '', $block['name']);
// include a template part from within the "template-parts/block" folder
if (file_exists(get_theme_file_path("/template-parts/blocks/content-{$slug}.php"))) {
include(get_theme_file_path("/template-parts/blocks/content-{$slug}.php"));
}
}
function wpdocs_mytheme_block_styles()
{
wp_enqueue_style('admin-css', get_stylesheet_directory_uri() . '/build/css/styles.min.css', '', '0.0.3');
wp_enqueue_script('admin-js', get_template_directory_uri() . '/build/js/scripts.min.js', array('jquery'), '0.0.3', true);
}
add_action('enqueue_block_editor_assets', 'wpdocs_mytheme_block_styles')
banner.php code:
<?php
$title = get_field('main_title');
$img = get_field('background_image');
$button = get_field('button');
?>
<section id="banner-section" style=" background-image:linear-gradient( rgba(67, 74, 122, 0.5), rgba(67, 74, 122, 0.5) ), url('<?= $img['url']; ?>');">
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-lg-10 text-center">
<h1 class="basic-slider-heading"> <?php echo $title ?> </h1>
<?php
if ($button) :
$button_url = $button['url'];
$button_title = $button['title'];
$button_target = $button['target'] ? $button['target'] : '_self';
?>
<button class="btn btn-shadow-malibu btn-bg-malibu-gradient bg-malibu-accent">
<?= $button_title ?>
</button>
<?php endif; ?>
</div>
</div>
</div>
</section>
var_dump( get_field('main_title'));
Note: I'm using WordPress v5.7.2 and ACF PRO v5.9.8
This is the documentation of get_field: https://www.advancedcustomfields.com/resources/get_field/
Note that there is an optional second parameter
$post_id (mixed) (Optional) The post ID where the value is saved. Defaults to the current post.
So, if your function works at a place and not at the other, then there are environmental differences between the two pages. It is possible that on the UI no post is being technically selected, in which case you need to pass the id of the post whose field you intend to get.

How to call a php class in wordpress?

I have a nice demo importer which is working fine but with a category post count issue so there is plugin which is fixing this and I'm trying to integrate into my demo importer library.
This plugin here is fixing the issue after demo import but requires to go into the plugin page selecting post types in order to click on submit button.
Well this is the plugin admin page:
<?php
if($_POST) {
if(!check_admin_referer('select_post_types_'.get_current_user_id() )){
echo 'That is not allowed'; exit;
}
$fixes = $_POST['fix'];
foreach($fixes AS $fix_id){
$fix = new Fix_Category_Count();
$fix->post_type = $fix_id;
if($fix->process()){
$updated = TRUE;
}
}
}
?>
<div>
<?php echo "<h2>" . __( 'Fix Category Count Settings', 'fix_category_count' ) . "</h2>"; ?>
<h3>Select Post Types to Fix</h3>
<form name="site_data_form" method="post" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>">
<div class="sa_block">
<?php
$post_types = get_post_types(array('public'=>TRUE));
foreach($post_types AS $post_type){
?>
<input type="checkbox" class="post_type" name="fix[]" id="fix_<?=$post_type; ?>" value="<?=$post_type; ?>" /> <label for="fix_<?=$post_type; ?>"><?=ucwords(preg_replace("/_/"," ",$post_type)); ?> (<?=$post_type;?>)</label><br />
<?php
}
?>
<br><br>
Select All |
Deselect All
</div>
</div>
<?php wp_nonce_field('select_post_types_'.get_current_user_id()); ?>
<div class="submit">
<input type="submit" name="Submit" value="<?php _e('Fix Categories Now', '' ) ?>" />
</div>
<?php if($updated){ ?>
<div class="updated"><p><strong><?php _e('Categories Updated.' ); ?></strong></p></div>
<? } ?>
</form>
</div>
<script type="text/javascript">
if(jQuery){
jQuery(document).ready(function($){
$('.select_boxes').click(function(e){
e.preventDefault();
if($(this).attr('rel')=='all'){
$('.post_type').each(function() {
this.checked = true;
});
}
else{
$('.post_type').each(function() {
this.checked = false;
});
}
});
});
}
</script>
So the CLASS of the plugin is here
I want to use only the class without the admin page with something like this:
ob_start();
if ( 'complete' == $response['process'] ) {
// Set imported menus to registered theme locations
$locations = get_theme_mod( 'nav_menu_locations' ); // registered menu locations in theme
$menus = wp_get_nav_menus(); // registered menus
if ( $menus ) {
foreach( $menus as $menu ) { // assign menus to theme locations
if( 'Main Menu' == $menu->name ) {
$locations['primary'] = $menu->term_id;
break;
}
}
}
set_theme_mod( 'nav_menu_locations', $locations ); // set menus to locations
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%postname%/');
$wp_rewrite->flush_rules();
// I want to add the plugin functionality as a last process here!
}
ob_end_clean();
I'm not a php developer yet but I would like to get this working without fixing the category count using the plugin page options but directly on the function above and with the php class provided by plugin.
Thank you.

how to add text widgets to wordpress sidebar using function?

I want to add text widget into my site sidebar when I activate theme. How can I do this using wordpress function or other methods? I'm using wordpress 4.1.
Help me. Thanks.
I don't know that what kind of widget you want to create, so i give you a simple example so you can understand.
Write blow code in functions.php or create an external file and include it into functions.php
First Register the Widget:
//========= Your Custom Widget
add_action( 'widgets_init', 'your_simple_widget' );
function your_simple_widget() {
register_widget( 'Your_Simple_Same_Widget' );
}
Second Create a widget body:
class Your_Simple_Same_Widget extends WP_Widget { }
NOTE: register_widget( 'Your_Simple_Same_Widget' ); name and class Your_Simple_Same_Widget and widget setup name must be same
There are four parts of widget in class
Widget Setup
How to display on front end
Update Widget values
Widget form or fields in admin panel
Ok Third in class Write this code like:
//========= Your Custom Widget Body
class Your_Simple_Same_Widget extends WP_Widget {
//=======> Widget setup
function Your_Simple_Same_Widget() {
/* Widget settings. */
$widget_ops = array( 'classname' => 'your class', 'description' => __('Your Class Description widget', 'your class') );
/* Widget control settings. */
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'your_widget' );
/* Create the widget. */
$this->WP_Widget( 'your_widget', __('Widget Heading', 'your class'), $widget_ops, $control_ops );
}
//=======> How to display the widget on the screen.
function widget($args, $widgetData) {
extract($args);
//=======> Our variables from the widget settings.
$your_widget_title = $widgetData['txtYourTitle'];
$your_widget_description = $widgetData['txtYourDescription'];
//=======> widget body
echo $before_widget;
echo '<div class="">';
if($your_widget_title){
echo '<h2>'.$your_widget_title .'</h2>';
}
if($your_widget_description){
echo '<p>'.$your_widget_description .'</p>';
}
echo "</div>";
echo $after_widget;
}
//=======>Update the widget
function update($new_widgetData, $old_widgetData) {
$widgetData = $old_widgetData;
//Strip tags from title and name to remove HTML
$widgetData['txtYourTitle'] = $new_widgetData['txtYourTitle'];
$widgetData['txtYourDescription'] = $new_widgetData['txtYourDescription'];
return $widgetData;
}
//=======>widget Display
function form($widgetData) {
//Set up some default widget settings.
$widgetData = wp_parse_args((array) $widgetData);
?>
<p>
<label for="<?php echo $this->get_field_id('txtYourTitle'); ?>">Widget Title:</label>
<input id="<?php echo $this->get_field_id('txtYourTitle'); ?>" name="<?php echo $this->get_field_name('txtYourTitle'); ?>" value="<?php echo $widgetData['txtYourTitle']; ?>" style="width:275px;" />
</p>
<p>
<label for="<?php echo $this->get_field_id('txtYourDescription'); ?>">Widget Title:</label>
<input id="<?php echo $this->get_field_id('txtYourDescription'); ?>" name="<?php echo $this->get_field_name('txtYourDescription'); ?>" value="<?php echo $widgetData['txtYourDescription']; ?>" style="width:275px;" />
</p>
<?php
}
}
?>
I hope this may help you.

Wordpress include plugin in post page

Hi I am trying to use the advanced layer slider in my wordpress post page. However my code pasted in the header.php file works only on the pages, not posts, I can see the shortcode showing up though in the top of the posts page. Is there anyway to include the code needed from the plugin easily?
Thanks in advanced,
James
Sorry about the formatting
Single.php
<?php
global $avia_config;
/*
* get_header is a basic wordpress function, used to retrieve the header.php file in your theme directory.
*/
get_header();
$title = __('Blog - Latest News', 'avia_framework'); //default blog title
$t_link = home_url('/');
$t_sub = "";
if(avia_get_option('frontpage') && $new = avia_get_option('blogpage'))
{
$title = get_the_title($new); //if the blog is attached to a page use this title
$t_link = get_permalink($new);
$t_sub = avia_post_meta($new, 'subtitle');
}
if( get_post_meta(get_the_ID(), 'header', true) != 'no') echo avia_title(array('heading'=>'strong', 'title' => $title, 'link' => $t_link, 'subtitle' => $t_sub));
?>
'>
<div class='container template-blog template-single-blog '>
<main class='content units <?php avia_layout_class( 'content' ); ?>' <?php avia_markup_helper(array('context' => 'content','post_type'=>'post'));?>>
<?php
/* Run the loop to output the posts.
* If you want to overload this in a child theme then include a file
* called loop-index.php and that will be used instead.
*
*/
get_template_part( 'includes/loop', 'index' );
//show related posts based on tags if there are any
get_template_part( 'includes/related-posts');
//wordpress function that loads the comments template "comments.php"
comments_template( '/includes/comments.php');
?>
<!--end content-->
</main>
<?php
$avia_config['currently_viewing'] = "blog";
//get the sidebar
get_sidebar();
?>
</div><!--end container-->
</div><!-- close default .container_wrap element -->
Page.php
<?php
global $avia_config;
/*
* get_header is a basic wordpress function, used to retrieve the header.php file in your theme directory.
*/
get_header();
if( get_post_meta(get_the_ID(), 'header', true) != 'no') echo avia_title();
?>
<div class='container_wrap container_wrap_first main_color <?php avia_layout_class( 'main' ); ?>'>
<div class='container'>
<main class='template-page content <?php avia_layout_class( 'content' ); ?> units' <?php avia_markup_helper(array('context' => 'content','post_type'=>'page'));?>>
<?php
/* Run the loop to output the posts.
* If you want to overload this in a child theme then include a file
* called loop-page.php and that will be used instead.
*/
$avia_config['size'] = avia_layout_class( 'main' , false) == 'entry_without_sidebar' ? '' : 'entry_with_sidebar';
get_template_part( 'includes/loop', 'page' );
?>
<!--end content-->
</main>
<?php
//get the sidebar
$avia_config['currently_viewing'] = 'page';
get_sidebar();
?>
</div><!--end container-->
</div><!-- close default .container_wrap element -->
Header.php
<?php
global $avia_config;
$style = $avia_config['box_class'];
$responsive = avia_get_option('responsive_layout','responsive');
$blank = isset($avia_config['template']) ? $avia_config['template'] : "";
$headerS = !$blank ? avia_header_setting() : "";
$headerMenu = $responsive ? avia_get_option('header_menu','mobile_drop_down') : "";
?>
class=" ">
" />
RSS2 Feed" href="" />
" />
';
?>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to such
* as styles, scripts, and meta tags.
*/
wp_head();
?>
'body')); ?>>
<div id='wrap_all'>
<?php if(!$blank){ ?>
<header id='header' class=' header_color <?php avia_is_dark_bg('header_color'); echo " ".$headerMenu; ?>' <?php avia_markup_helper(array('context' => 'header','post_type'=>'forum'));?>>
<?php
if($responsive && $headerMenu == 'mobile_slide_out')
{
echo '<a id="advanced_menu_toggle" href="#" '.av_icon_string('mobile_menu').'></a>';
echo '<a id="advanced_menu_hide" href="#" '.av_icon_string('close').'></a>';
}
$social_args = array('outside'=>'ul', 'inside'=>'li', 'append' => '');
//subheader, only display when the user chooses a social header
if(strpos($headerS,'social_header') !== false)
{
?>
<div id='header_meta' class='container_wrap container_wrap_meta'>
<div class='container'>
<?php
/*
* display the themes social media icons, defined in the wordpress backend
* the avia_social_media_icons function is located in includes/helper-social-media-php
*/
if(strpos($headerS,'bottom_nav_header') === false) avia_social_media_icons($social_args);
//display the small submenu
echo "<nav class='sub_menu' ".avia_markup_helper(array('context' => 'nav', 'echo' => false)).">";
$avia_theme_location = 'avia2';
$avia_menu_class = $avia_theme_location . '-menu';
$args = array(
'theme_location'=>$avia_theme_location,
'menu_id' =>$avia_menu_class,
'container_class' =>$avia_menu_class,
'fallback_cb' => '',
'container'=>'',
'echo' =>false
);
$nav = wp_nav_menu($args);
echo $nav;
$phone = avia_get_option('phone');
$phone_class = !empty($nav) ? "with_nav" : "";
if($phone) echo "<div class='phone-info {$phone_class}'><span>{$phone}</span></div>";
/*
* Hook that can be used for plugins and theme extensions (currently: the wpml language selector)
*/
do_action('avia_meta_header');
echo '</nav>';
?>
</div>
</div>
<?php } ?>
<div id='header_main' class='container_wrap container_wrap_logo'>
<?php
/*
* Hook that can be used for plugins and theme extensions (currently: the woocommerce shopping cart)
*/
do_action('ava_main_header');
?>
<div class='container'>
<?php
/*
* display the theme logo by checking if the default logo was overwritten in the backend.
* the function is located at framework/php/function-set-avia-frontend-functions.php in case you need to edit the output
*/
echo avia_logo(AVIA_BASE_URL.'images/layout/logo.png', false, 'strong');
if(strpos($headerS,'social_header') !== false && strpos($headerS,'bottom_nav_header') !== false) avia_social_media_icons($social_args);
/*
* display the main navigation menu
* modify the output in your wordpress admin backend at appearance->menus
*/
$extraOpen = $extraClose = "";
if(strpos($headerS,'bottom_nav_header') !== false){ $extraClose = "</div></div><div id='header_main_alternate' class='container_wrap'><div class='container'>"; }
echo $extraClose;
echo "<nav class='main_menu' data-selectname='".__('Select a page','avia_framework')."' ".avia_markup_helper(array('context' => 'nav', 'echo' => false)).">";
$avia_theme_location = 'avia';
$avia_menu_class = $avia_theme_location . '-menu';
$args = array(
'theme_location' => $avia_theme_location,
'menu_id' => $avia_menu_class,
'container_class' => $avia_menu_class,
'fallback_cb' => 'avia_fallback_menu',
'walker' => new avia_responsive_mega_menu()
);
wp_nav_menu($args);
echo '</nav>';
/*
* Hook that can be used for plugins and theme extensions
*/
do_action('ava_after_main_menu');
?>
<!-- end container-->
</div>
<!-- end container_wrap-->
</div>
<div class='header_bg'></div>
<!-- end header -->
</header>
<?php } //end blank check ?>
<div id='main'>

Categories