wordpress: overwrite public static function through functions.php - wordpress

I have tried this article: Modify Wordpress plugin function in functions.php not working.
I have a plugin (Wordpress_seo). It has a folder "frontend" in it and class-breadcrumbs.php file with WPSEO_Breadcrumbs class and a public static function breadcrumb. I need to overwrite it in functions.php.
I am pretty new to wordpress, so I might have missed some solution. Here is my current code:
add_filter('filter_breadcrumb', 'mytheme_breadcrumb');
function mytheme_breadcrumb($before = '', $after = '', $display = true){
if ( ! ( self::$instance instanceof self ) ) {
self::$instance = new self();
}
// Remember the last used before/after for use in case the object goes __toString().
self::$before = $before;
self::$after = $after;
$output = $before . '<!--1-->'.self::$instance->output.'<!--2-->' . $after;
if ( $display === true ) {
echo $output;
return true;
}
else {
return $output;
}
}
I copied the whole function and added the '' for testing purposes, but it doesn't work. Can anyone tell me if I am doing something wrong?
thanks

Related

why does add_action or add_shortcode not create an instance of a class

I wanted to create an instance of a class when my program start add_shortcode(), but I find it not worked.
Does anyone can help me solve this problem?
The following is my code:
class Test{
private $infos;
function get_info() {
if ( isset($_REQUEST['my_info']) ) {
$infos = $_REQUEST['my_info'];
if (get_option('my_url')){
update_option('my_url', $infos);
}else{
add_option('my_url', $infos);
}
}
die();
}
function salcodes_year() {
echo plugin_dir_url(__FILE__) . 'src/my_test1.php';
require_once plugin_dir_url(__FILE__) . 'src/my_test1.php';
$my_crawler = new Test_one($infos);
return get_option('my_url');
}
function js2php_register(){
add_action( 'wp_ajax_crawler_info', array($this, 'get_info') );
add_action( 'wp_ajax_nopriv_crawler_info', array($this, 'get_info') );
add_shortcode( 'current_year', array($this, 'salcodes_year') );
}
}
$test = new Test;
$test->js2php_register();
I get error Fatal error: Uncaught Error: Class 'Test_one' not found when I run my code.
The following is my_test1.php:
<?php
class Test_one{
function a(){
$this->a1='aaa';
}
function b(){
echo 'a1:'.$this->a1;
}
function c(){
$this->a();
$this->b();
}
}
Through my testing I found no matter how do I put these code, require_once plugin_dir_url(__FILE__) . 'src/my_test1.php'; & $my_crawler = new Test_one($infos);, in the function of add_shortcode() or add_action('wp_ajax_') both are not work...
Does anyone help me, Please
Thanks

Polylang + ACF - Fields Group on front page is not displaying on translated pages

I've just installed Polylang (Free version) and I have field group that is set to be displayed on front-page.
In the admin, fields are displaying correctly on the main language's front page but not on the translated front-page.
I've searched to see what could go wrong and it's obviously because of ACF that is only checking if we are on the front page with get_option('page_on_front').
And polylang doesn't seems to filter the value to set the right front-page.
So I found this mu-plugin:
<?php
class ACF_Page_Type_Polylang {
// Whether we hooked page_on_front
private $filtered = false;
public function __construct() {
add_filter( 'acf/location/rule_match/page_type', array( $this, 'hook_page_on_front' ) );
}
public function hook_page_on_front( $match ) {
if ( ! $this->filtered ) {
add_filter( 'option_page_on_front', array( $this, 'translate_page_on_front' ) );
// Prevent second hooking
$this->filtered = true;
}
return $match;
}
public function translate_page_on_front( $value ) {
if ( function_exists( 'pll_get_post' ) ) {
$value = pll_get_post( $value );
}
return $value;
}
}
new ACF_Page_Type_Polylang();
but it does not resolve the issue and i don't know why, the code seems correct.
If I only take this part :
add_filter( 'option_page_on_front', array( $this, 'translate_page_on_front' ) );
and convert it to :
add_filter( 'option_page_on_front',function() { return '346' });
(346 is the translated front-page ID)
it filters properly the option page_on_front and my fields are displaying correctly.
Can you help me make the mu-plugin works ?
I've found a way to make it work but I don't know if it's the right way ... can you please tell me ?
<?php
class ACF_Page_Type_Polylang {
// Whether we hooked page_on_front
private $filtered = false;
public function __construct() {
add_filter( 'acf/location/rule_match/page_type', array( $this, 'hook_page_on_front' ) );
}
public function hook_page_on_front( $match ) {
// Abort if polylang not activated
if ( !function_exists( 'pll_get_post' ) ) {
return $match;
}
// Get the main language front page
$front_page = (int) get_option('page_on_front');
// Get the translated page of the curent language
$translated_page = pll_get_post($front_page);
// Check if it's the same as the current page and set match to true if so
if($translated_page === get_the_id()) {
$match = true;
}
return $match;
}
}
new ACF_Page_Type_Polylang();

How to export all rows as CSV in ModelAdmin (SilverStripe 3.1)?

Apparently the GridFieldExportButton only exports the currently visible data-set (paginated). Is there a way to make it export all the rows from a model?
Or alternatively: Is there a way to show all rows (eg. bypass pagination), so that the user can perform an export after showing all the rows? I don't want to show all rows all the time (which would probably be possible by setting ModelAdmin::set_page_length(<ridiculouslyHighNumber>);) but only on demand.
You can override ModelAdmin::getExportFields() to define the columns you want to export.
The method needs to return an array with column name as the key, and the db field as the value.
For example:
class MyCustomModelAdmin extends ModelAdmin {
....
public function getExportFields() {
return array(
'FirstName' => 'FirstName',
'Surname' => 'Surname',
'Age' => 'Age'
);
}
}
Solved it by creating a custom subclass of the GridFieldExportButton and using this for my models. The key is to use $gridField->getList(); instead of $gridField->getManipulatedList(); in the generateExportFileData method.
Here's the complete class for anybody interested:
class GridFieldExportAllButton extends GridFieldExportButton {
/**
* Generate export fields for CSV.
*
* #param GridField $gridField
* #return array
*/
public function generateExportFileData($gridField) {
$separator = $this->csvSeparator;
$csvColumns = ($this->exportColumns)
? $this->exportColumns
: singleton($gridField->getModelClass())->summaryFields();
$fileData = '';
$columnData = array();
$fieldItems = new ArrayList();
if($this->csvHasHeader) {
$headers = array();
// determine the CSV headers. If a field is callable (e.g. anonymous function) then use the
// source name as the header instead
foreach($csvColumns as $columnSource => $columnHeader) {
$headers[] = (!is_string($columnHeader) && is_callable($columnHeader)) ? $columnSource : $columnHeader;
}
$fileData .= "\"" . implode("\"{$separator}\"", array_values($headers)) . "\"";
$fileData .= "\n";
}
$items = $gridField->getList();
foreach($items as $item) {
$columnData = array();
foreach($csvColumns as $columnSource => $columnHeader) {
if(!is_string($columnHeader) && is_callable($columnHeader)) {
if($item->hasMethod($columnSource)) {
$relObj = $item->{$columnSource}();
} else {
$relObj = $item->relObject($columnSource);
}
$value = $columnHeader($relObj);
} else {
$value = $gridField->getDataFieldValue($item, $columnSource);
}
$value = str_replace(array("\r", "\n"), "\n", $value);
$columnData[] = '"' . str_replace('"', '\"', $value) . '"';
}
$fileData .= implode($separator, $columnData);
$fileData .= "\n";
$item->destroy();
}
return $fileData;
}
}
Thanks for this!
I had to use this for Members GF in Security Admin.
Created an extension for anyone interested.
class SecurityAdminExtension extends Extension{
function updateEditForm($form){
$gf = $form->Fields()->fieldByName('Root.Users.Members');
$gfConfig = $gf->getConfig();
$gfConfig->removeComponentsByType('GridFieldExportButton');
$gfConfig->addComponent(new GridFieldExportAllButton());
}
}
I while back, I created a little plugin to make it easy to export DataObjects to CSV or Excel files.
https://github.com/firebrandhq/excel-export
It comes with a button you can add to a grid field.
It's got a dependency on PHP-Excel.

addToolbar in joomla 3.0

Added toolbar in joomla 3.0 html.php file. When the addNew button is clicked it displays
An error has occurred. 0 Invalid controller:
name='Comboscategories', format=''
html.php file as follows.
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
class ComboscategoriesViewsStatisticsHtml extends JViewHtml
{
function render()
{
$app = JFactory::getApplication();
//retrieve task list from model
$model = new ComboscategoriesModelsStatistics();
$this->stats = $model->getStats();
$this->addToolbar();
/*$this->displayComboslist();*/
//display
return parent::render();
}
protected function addToolbar()
{
$canDo = ComboscategoriesHelpersLendr::getActions();
// Get the toolbar object instance
$bar = JToolBar::getInstance('toolbar');
JToolbarHelper::title(JText::_('Combos Category'));
JToolBarHelper::addNew('Comboscategories.add');
/* JToolbarHelper::preferences('com_comboscategories');*/
JToolBarHelper::save();
JToolBarHelper::cancel();
JToolBarHelper::deleteList();
JToolBarHelper::publishList();
JToolBarHelper::unpublishList();
}
}
controller.php(display.php)
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
class ComboscategoriesControllersDisplay extends JControllerBase
{
public function execute()
{
// Get the application
$app = $this->getApplication();
// Get the document object.
$document = JFactory::getDocument();
$viewName = $app->input->getWord('view', 'statistics');
$viewFormat = $document->getType();
$layoutName = $app->input->getWord('layout', 'default');
$app->input->set('view', $viewName);
// Register the layout paths for the view
$paths = new SplPriorityQueue;
$paths->insert(JPATH_COMPONENT . '/views/' . $viewName . '/tmpl', 'normal');
$viewClass = 'ComboscategoriesViews' . ucfirst($viewName) . ucfirst($viewFormat);
$modelClass = 'ComboscategoriesModels' . ucfirst($viewName);
$view = new $viewClass(new $modelClass, $paths);
$view->setLayout($layoutName);
// Render our view.
echo $view->render();
return true;
}
}
I searched related to this but i dont find the solution. kindly help me to sort this
Hi im new to joomla but i think that your classes have bad names. it Should be ComboscategoriesViewStatisticsHtml or ComboscategoriesControllerDisplay
You have to use the name of the model: if you have a controller called ComboscategoriesControllersDisplay your call should be JToolBarHelper::addNew('display.add').
Best read this: http://docs.joomla.org/J3.x:Developing_a_MVC_Component/Adding_backend_actions

Restrict menu tree to first level

I've been struggling a while in order to get my primary links to display only the first level entries (roots). I have the following code in my template.php :
I've tried changing the $level variable to 0 but no effect. I don't know where (the hell) to stop the recursion.
function supertheme_navigation_links($menu_name, $level = 2) {
// Don't even bother querying the menu table if no menu is specified.
if (empty($menu_name)) {
return array();
}
// Get the menu hierarchy for the current page.
$tree_page = menu_tree_page_data($menu_name);
// Also get the full menu hierarchy.
$tree_all = menu_tree_all_data($menu_name);
// Go down the active trail until the right level is reached.
while ($level-- > 0 && $tree_page) {
// Loop through the current level's items until we find one that is in trail.
while ($item = array_shift($tree_page)) {
if ($item['link']['in_active_trail']) {
// If the item is in the active trail, we continue in the subtree.
$tree_page = empty($item['below']) ? array() : $item['below'];
break;
}
}
}
return supertheme_navigation_links_level($tree_page, $tree_all);
}
/**
* Helper function for supertheme_navigation_links to recursively create an array of links.
* (Both trees are required in order to include every menu item and active trail info.)
*/
function supertheme_navigation_links_level($tree_page, $tree_all) {
$links = array();
foreach ($tree_all as $key => $item) {
$item_page = $tree_page[$key];
$item_all = $tree_all[$key];
if (!$item_all['link']['hidden']) {
$l = $item_all['link']['localized_options'];
$l['href'] = $item_all['link']['href'];
$l['title'] = $item_all['link']['title'];
if ($item_page['link']['in_active_trail']) {
if (empty($l['attributes']['class'])) {
$l['attributes']['class'] = 'active-trail';
}
else {
$l['attributes']['class'] .= ' active-trail';
}
}
if ($item_all['below']) {
$l['children'] = supertheme_navigation_links_level($item_page['below'], $item_all['below']);
}
// Keyed with unique menu id to generate classes from theme_links().
$links['menu-'. $item_all['link']['mlid']] = $l;
}
}
return $links;
}
/**
* Return a themed set of links. (Extended to support multidimensional arrays of links.)
*/
function supertheme_links($links, $attributes = array('class' => 'links')) {
$output = '';
if (count($links) > 0) {
$output = '<ul'. drupal_attributes($attributes) .'>';
$num_links = count($links);
$i = 1;
foreach ($links as $key => $link) {
$class = $key;
// Add first, last and active classes to the list of links to help out themers.
if ($i == 1) {
$class .= ' first';
}
if ($i == $num_links) {
$class .= ' last';
}
if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))) {
$class .= ' active';
}
// Added: if the link has child items, add a haschildren class
if (isset($link['children'])) {
$class .= ' haschildren';
}
$output .= '<li'. drupal_attributes(array('class' => $class)) .'>';
if (isset($link['href'])) {
// Pass in $link as $options, they share the same keys.
$output .= l($link['title'], $link['href'], $link);
}
else if (!empty($link['title'])) {
// Some links are actually not links, but we wrap these in <span> for adding title and class attributes
if (empty($link['html'])) {
$link['title'] = check_plain($link['title']);
}
$span_attributes = '';
if (isset($link['attributes'])) {
$span_attributes = drupal_attributes($link['attributes']);
}
$output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
}
// Added: if the link has child items, print them out recursively
if (isset($link['children'])) {
$output .= "\n" . theme('links', $link['children'], array());
}
$i++;
$output .= "</li>\n";
}
$output .= '</ul>';
}
return $output;
}
function supertheme_primary_links() {
return supertheme_navigation_links(variable_get('menu_primary_links_source', 'primary-links'
));
}
3 comments:
Not totally sure what you meant when you said you tried to change $level to 0, but then it will not enter in the loop: while ($level-- > 0 && $tree_page)
To be able to stop a recursion, the recursive function needs to have an argument with the depth. So INSIDE the recursive function you decide when to stop: if ($depth <1) { return; } and everytime you call the recursive funcion you call it with $depth-1
If you want this functionality 'out-of-the-box', try http://drupal.org/project/menu_block , or get some inspiration from its code: (see menu_tree_depth_trim function)
I believe, that if you set your menu to be non-expanded under menu settings that Drupal will handle the rest for you.
Another option would be to use nice menus which mainly is used to show expandable menus, but also can be used to control the level of menu expansion.

Resources