lundi 5 octobre 2015

Make code snippet into a foreach loop

I have a piece of code which is used to replace double dashes for commas in a wordpress taxonomy called “authors” before displaying values to the end user.

This is working great, but now I need to apply it to several different taxonomies, no just “authors” but also “printers”, “translators”, etc.

My idea was to build an array of taxonomies instead of a single variable and then use a foreach loop to apply the find and replace to each of them, but no matter how I try it I can’t seem to make it work…

Any idea how to make the following code into a foreach loop if $custom_taxonomy_type was an array?

This is the code that is currently working for a single taxonomy.

if(!is_admin()){ // make sure the filters are only called in the frontend

$custom_taxonomy_type = 'authors';  // here goes your taxonomy type

function comma_taxonomy_filter($tag_arr){
    global $custom_taxonomy_type;
    $tag_arr_new = $tag_arr;
    if($tag_arr->taxonomy == $custom_taxonomy_type && strpos($tag_arr->name, '--')){
        $tag_arr_new->name = str_replace('--',', ',$tag_arr->name);
    }
    return $tag_arr_new;    
}
add_filter('get_authors', comma_taxonomy_filter);

function comma_taxonomies_filter($tags_arr){
    $tags_arr_new = array();
    foreach($tags_arr as $tag_arr){
        $tags_arr_new[] = comma_taxonomy_filter($tag_arr);
    }
    return $tags_arr_new;
}
add_filter('get_the_taxonomies',    comma_taxonomies_filter);
add_filter('get_terms',             comma_taxonomies_filter);
add_filter('get_the_terms',         comma_taxonomies_filter);

}

As requested by @Epodax here are the two things I've tried so far. Both result in a blank page:

if(!is_admin()){ // make sure the filters are only called in the frontend

    $custom_taxonomy_type_array = array('authors', 'printer');  // here goes your taxonomy type

    foreach ($custom_taxonomy_type_array as $custom_taxonomy_type) {
        function comma_taxonomy_filter($tag_arr){
            global $custom_taxonomy_type;
            $tag_arr_new = $tag_arr;
            if($tag_arr->taxonomy == $custom_taxonomy_type && strpos($tag_arr->name, '--')){
                $tag_arr_new->name = str_replace('--',', ',$tag_arr->name);
            }
            return $tag_arr_new;    
        }
        add_filter('get_'.$custom_taxonomy_type, comma_taxonomy_filter);

        function comma_taxonomies_filter($tags_arr){
            $tags_arr_new = array();
            foreach($tags_arr as $tag_arr){
                $tags_arr_new[] = comma_taxonomy_filter($tag_arr);
            }
            return $tags_arr_new;
        }
        add_filter('get_the_taxonomies',    comma_taxonomies_filter);
        add_filter('get_terms',             comma_taxonomies_filter);
        add_filter('get_the_terms',         comma_taxonomies_filter);
    }


}

and

if(!is_admin()){ // make sure the filters are only called in the frontend

    $custom_taxonomy_type_array = array('authors', 'printer');  // here goes your taxonomy type

    function comma_taxonomy_filter($tag_arr){
        foreach ($custom_taxonomy_type_array as $custom_taxonomy_type) {
            global $custom_taxonomy_type;
            $tag_arr_new = $tag_arr;
            if($tag_arr->taxonomy == $custom_taxonomy_type && strpos($tag_arr->name, '--')){
                $tag_arr_new->name = str_replace('--',', ',$tag_arr->name);
            }
            return $tag_arr_new;    
        }
    }
    foreach ($custom_taxonomy_type_array as $custom_taxonomy_type) {
        add_filter('get_'.$custom_taxonomy_type, comma_taxonomy_filter);
    }

    function comma_taxonomies_filter($tags_arr){
        foreach ($custom_taxonomy_type_array as $custom_taxonomy_type) {
            $tags_arr_new = array();
            foreach($tags_arr as $tag_arr){
                $tags_arr_new[] = comma_taxonomy_filter($tag_arr);
            }
            return $tags_arr_new;
        }
    }
    foreach ($custom_taxonomy_type_array as $custom_taxonomy_type) {
        add_filter('get_the_taxonomies',    comma_taxonomies_filter);
        add_filter('get_terms',             comma_taxonomies_filter);
        add_filter('get_the_terms',         comma_taxonomies_filter);
    }

}



via Chebli Mohamed

Get prefix from multiple wordpress sites with different databases with external script

I am trying to get the prefix of multiple databases of wordpress installations with different prefixes. But failing to do this and is getting me only the first table prefix for all files:

Folder structure (basic - has all required wordpress files):

home:
+---cpanel1
|   \---public_html
|       +---wp-load.php => $table_prefix = 'wp1_';
+---cpanel2
|   \---public_html
|       +---wp-load.php => $table_prefix = 'wp2_';
\---cpanel3
    \---public_html
        +---wp-load.php => $table_prefix = 'wp3_';
+---get_prefixes.php

Script get_prefixes.php (PHP):

$myfile = '/wp-load.php';
class execute_sql_code {
    public function __construct($myfile) {
        $this->main_work($myfile);
    }
    public $cpanels = array(
            'cpanel1',
            'cpanel2',
            'cpanel3'
    );
    public function main_work($myfile) {
        foreach ($this->cpanels as $cpanel) {
            $the_file = $cpanel.'/public_html'.$myfile;
            var_dump($the_file);
            require($the_file);
            global $wpdb;
            var_dump($wpdb->prefix);
        }
    }
}
new execute_sql_code($myfile);

var_dump($the_file) => OUTPUTS CORRECTLY every path.

var_dump($wpdb->prefix) => OUTPUTS WRONG wp1_ for each iteration:

CURRENT OUTPUT:

Iteration 1 => cpanel1/public_html/wp-load.php => $wpdb->prefix = wp1_

Iteration 2 => cpanel2/public_html/wp-load.php => $wpdb->prefix = wp1_

Iteration 3 => cpanel3/public_html/wp-load.php => $wpdb->prefix = wp1_

EXPECTED OUTPUT:

Iteration 1 => cpanel1/public_html/wp-load.php => $wpdb->prefix = wp1_

Iteration 2 => cpanel2/public_html/wp-load.php => $wpdb->prefix = wp2_ // normal

Iteration 3 => cpanel3/public_html/wp-load.php => $wpdb->prefix = wp3_ // normal



via Chebli Mohamed

preg_match(): Compilation failed: unmatched parentheses at offset 73

I could not figure out why the expression is incorrect.

            foreach ( (array) $rewrite as $match => $query ) {
                // If the requesting file is the anchor of the match, prepend it to the path info.
                if ( ! empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request )
                    $request_match = $req_uri . '/' . $request;
                // LINE 207
                if ( preg_match( "#^$match#", $request_match, $matches ) || preg_match( "#^$match#", urldecode($request_match), $matches ) ) {

                    if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
                        // This is a verbose page match, let's check to be sure about it.
                        if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
                            continue;
                    }

                    // Got a match.
                    $this->matched_rule = $match;
                    break;
                }

Warning: preg_match() [function.preg-match]: Compilation failed: unmatched parentheses at offset 73 in class-wp.php on line 207



via Chebli Mohamed

Query with meta key is serialized array

I've made a custom query containing a meta query but some fields are serialized arrays. Is there a way to get the value from that array? Everything I've tried so far won't work.

$query_args = array(
                    'post_type'         => 'yacht',
                    '_meta_or_tax'      => true,
                    'tax_query'         => array(
                        'relation'      => 'AND',
                        array(
                            'taxonomy'  => 'manufacturers',
                            'field'     => 'id',
                            'terms'     => $_GET['manufacturer']
                        ),
                        array(
                            'taxonomy'  => 'category',
                            'field'     => 'id',
                            'terms'     => $_GET['cat'],
                        )
                    ),
                    'posts_per_page'    => -1,
                    'meta_query'        => array(
                        'relation'      => 'AND',
                        array(
                         'key'          => 'yachts_length',
                         'value'        => array($_GET['min_length'], $_GET['max_length']),
                         'compare'      => 'BETWEEN',
                         'type'         => 'NUMERIC',
                        ),
                        array(
                         'key'          => 'yachts_price',
                         'value'        => array($_GET['min_price'], $_GET['max_price']),
                         'compare'      => 'BETWEEN',
                         'type'         => 'NUMERIC',
                        ),
                        array(
                         'key'          => 'yachts_year',
                         'value'        => array($_GET['min_year'], $_GET['max_year']),
                         'compare'      => 'BETWEEN',
                         'type'         => 'NUMERIC',
                        ),
                        array(
                         'key'          => 'yachts_fuel',
                         'value'        => $_GET['fuel'],
                         'compare'      => 'LIKE',
                        ),
                        array(
                         'key'          => 'yachts_cabins',
                         'value'        => $_GET['cabins'],
                         'compare'      => 'LIKE',
                         'type'         => 'NUMERIC',
                        ),
                        array(
                         'key'          => 'yachts_engine_type',
                         'value'        => $_GET['engine_type'],
                         'compare'      => 'LIKE',
                        ),
                        array(
                         'key'          => 'yachts_en',
                         'value'        => $_GET['engines'],
                         'compare'      => 'LIKE',
                         'type'         => 'NUMERIC',
                        ),
                        array(
                         'key'          => 'yachts_drive',
                         'value'        => $_GET['drive_type'],
                         'compare'      => 'LIKE',
                        ),
                    )
                );

                $yacht_query = new WP_Query( $query_args );

yachts_cabins, yachts_fuel, yachts_engine_type, yachts_en, yachts_type are serialized arrays.



via Chebli Mohamed

Date and Datetime using PHPExcel function writes in excel as Text

I have a problem with PHPExcel function, this is my code:

<?php
# Load slim WP
define( 'WP_USE_THEMES', false );
require( './wp-load.php' );
# http://ift.tt/AkDVWF
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
global $wpdb;
$query = "Select
  tsales_funnel.ID As ID,
  wp_users.display_name As Darijuma_vaditajs,
  tcportal_starpnieks.Cp_Name As Starpnieks,
  tcportal_stucture.Cp_Name As OWCA,
  n_products.Product_Nos As Produkts,
  tsales_funnel_mrecord.Product_type as Produkta_kods,
    tsales_funnel.Sanems_date as Saņēmšanas_datums,
  tsales_funnel_mrecord.Deadline As Deadline,
  n_sf_statusi.nosaukums_lv As Statuss,
  tsales_funnel_clients.Reg_nr As Klienta_Regnr,
  tfirmas_reg.name_in_quotes As Klients,
  tsales_funnel_mrecord.Faze_date as Faze_date,
  n_sf_fazes.nosaukums_lv As Faze,
  tsales_funnel_mrecord.Summa As Apdrošīnājuma_summa,
  tsales_funnel_mrecord.Vien_skaits As TRL_skaits,
  tsales_funnel_mrecord.Compensa_cena,
  tsales_funnel_mrecord.Tirgus_cena,
  wp_users02.display_name As Riska_parakstitajs,
  comm.Comment as Aizveršanas_komentārs
From
  tsales_funnel Left Join
  tsales_funnel_mrecord On tsales_funnel.ID = tsales_funnel_mrecord.Funnel_ID
  Left Join
  tcportal_starpnieks On tcportal_starpnieks.Cp_code = tsales_funnel.Starpnieks
  Left Join
  tcportal_stucture On tcportal_stucture.Cp_code = tsales_funnel.OWCA Left Join
  tsales_funnel_clients On tsales_funnel_clients.Funnel_ID = tsales_funnel.ID
  Left Join
  tfirmas_reg On tfirmas_reg.regcode = tsales_funnel_clients.Reg_nr Left Join
  wp_users On tsales_funnel.Darijuma_vaditajs = wp_users.user_login Left Join
  n_sf_statusi On n_sf_statusi.id = tsales_funnel.Statuss
  Left Join n_sf_fazes on tsales_funnel_mrecord.Product_faze = n_sf_fazes.id
   Left Join
  n_products On tsales_funnel_mrecord.Product_type = n_products.Product_Code
  Left Join
  (SELECT * FROM tsales_funnel_comments WHERE Comm_type = 4) as comm On tsales_funnel.ID = comm.Funnel_ID
  Left Join
  wp_users As wp_users02
    On wp_users02.user_login = tsales_funnel_mrecord.Risk_acceptance
WHERE 
tsales_funnel_clients.Tips_Galvenais = 1
";
$error = "Error: the query failed...
    <pre style='width:700px;word-wrap:break-word;white-space:normal;'>$query</pre>";
$result = $wpdb->get_results( $query, ARRAY_A ) or wp_die( $error );
$objPHPExcel = new PHPExcel(); 
$objPHPExcel->getProperties()
        ->setCreator("user")
            ->setLastModifiedBy("user")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 0; 
// Sheet cells
$cell_definition = array(
    'A' => 'ID',
    'B' => 'Darijuma_vaditajs',
    'C' => 'Starpnieks',
    'D' => 'OWCA',
    'E' => 'Produkts',
    'F' => 'Produkta_kods',
    'G' => 'Saņēmšanas_datums',
    'H' => 'Deadline',
    'I' => 'Statuss',
    'J' => 'Klienta_Regnr',
    'K' => 'Klients',
    'L' => 'Faze_date',
    'M' => 'Faze',
    'N' => 'Apdrošīnājuma_summa',
    'O' => 'TRL_skaits',
    'P' => 'Compensa_cena',
    'Q' => 'Tirgus_cena',
    'R' => 'Riska_parakstitajs',
    'S' => 'Aizveršanas_komentārs'
);
// Build headers
foreach( $cell_definition as $column => $value )
    $objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value ); 
// Build cells
while( $rowCount < count($result) ){ 
    $cell = $rowCount + 2;
    foreach( $cell_definition as $column => $value ){
        switch($column) {
            case 'G';
            case 'H';
            $val = '=DATEVALUE("'.date('Y.m.d',strtotime($result[$rowCount][$value])).'")';
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        break;
        case 'L';
        $val = date('Y.m.d H:i:s',strtotime($result[$rowCount][$value]));
        $objPHPExcel->getActiveSheet()->getStyle($column.$cell)
            ->getNumberFormat()
            ->setFormatCode("yyyy.mm.dd h:mm");
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        break;
        default;
        $val = $result[$rowCount][$value];
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        }
        }
    $rowCount++; 
} 
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="iPortal_Atskaite_'.date('Y-m-d_H.i.s', strtotime('+3 hour')).'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;

I'm using switch for columns, where I need a different cell format.

Column G and H I need format 2015.10.05 (yyyy.mm.dd) And for column L 2015.10.05 12:03 (yyyy.mm.dd H:i).

Function getStyle() doesn't work, and returns the same value. If output as =datevalue, which is excel function, all is ok, but it doesn't work with time.

Also, if I press edit cell in excel and press enter, that date converts to normal date for excel and all works fine.

So, the problem is with output formatting. How can I define it? For other columns, for example for numbers, all is ok.



via Chebli Mohamed

wp post title in foundation tooltip

I would like to show the next/prev post link title in a tooltip, i tried several options, but it won't display it. The place is "SHOW POST TITLE HERE". the code:

<?php next_post_link('%link', '<span data-tooltip aria-haspopup="true" class="has-tip tip-bottom" title="SHOW POST TITLE HERE"><i class="fa fa-angle-left fa-2x"></i></span>
'); ?>

thnx in advance



via Chebli Mohamed

Wordpress posts, link to category pages

Within this wordpress function:

function ct_post_nav() { ?>
        <ul>
           <li class="post-nav-all">
              <?php $linktitelposts = get_cat_ID( $cat_name );          
                 if ($linktitelposts == 'blogs' )
                 {$linktitelposts = '<a href="#">Lees alle blogs</a>';}
                 if ($linktitelposts == 'vacatures')
                 {$linktitelposts = '<a href="#">Lees alle vacatures</a>';}
             ?> 
           </li>
        </ul>
    </div><!-- .nav-links -->
</nav><!-- .navigation -->

I want a link back to the categorie pages inside the li. The php lines that are in there now are what I tried, but of course it does not work. Is there a way to get a link that changes per category?



via Chebli Mohamed