Wordpress wp_redirect issue - wordpress

I am having some trouble with wp_redirect in my plugin.
Here is my code:
public function update($year, $edit_id, $column1, $column2) {
global $wpdb;
$table_name = $wpdb->prefix . 'tableName_'.$year;
$Column1 = intval($column1);
$Column2 = intval($column2);
$NewTotal = ($Column1 + $Column2);
$wpdb->update($table_name, array('Column1' => $Column1, 'Column2' => $Column2, 'Column3' => $NewTotal), array('month_id' => $edit_id));
wp_redirect(get_option('siteurl').'/wp-admin/admin.php?page=myplugin');
exit();
}
When I execute:
I get the following error:
Warning: Cannot modify header information - headers already sent by (output started at /home/.../public_html/wp-admin/includes/template.php:1953) in /home/.../public_html/wp-includes/pluggable.php on line 1171
Any help would be appreciated.
Thanks

Can you please add below code in your functions.php
function app_output_buffer() {
ob_start();
} // soi_output_buffer
add_action('init', 'app_output_buffer');

Related

How to return content in <head> through a wordpress API endpoint

So I've been trying to extend the Wordpress API to fetch the content which Wordpress outputs in the <head>.
I've registered my endpoint like so in functions.php of my theme:
add_action('rest_api_init', function () {
register_rest_route( 'hs/v1', 'header',array(
'methods' => 'GET',
'callback' => 'get_head_content'
));
});
And the callback looks like below but only returns empty arrays for each key:
function get_head_content() {
$result = [];
$result['scripts'] = [];
$result['styles'] = [];
// Print all loaded Scripts
global $wp_scripts;
foreach( $wp_scripts->queue as $script ) :
$result['scripts'][] = $wp_scripts->registered[$script]->src . ";";
endforeach;
// Print all loaded Styles (CSS)
global $wp_styles;
foreach( $wp_styles->queue as $style ) :
$result['styles'][] = $wp_styles->registered[$style]->src . ";";
endforeach;
return $result;
}
So my guess is that the get_head_content returns nothing since nothing has been enqueued because I'm not actually triggering the queue by hitting the API endpoint. This doesn't really output the whole <head> as a string either which would be my main objective.
Does anyone know how to achieve this?
Appreciate the help!
You can use the output buffer and get_header:
function get_head_content() {
ob_start();
get_header();
$header = ob_get_contents();
ob_end_clean();
return $header ;
}

Create a shortcode for a handmade plugin in Wordpress

I'm working on WordPress actually and created a plugin from scratch, fully working on admin page.
The plugin allow you to add country and languages related (USA->English|Sapnish for example)
I am using Class and constructor for the plugin's functions
Now I would like to created a select with country and depending on country another select with languages. I know how to create this in js/html but I can't find a way to get the data from the plugin.
I tried :
Create a function (in the plugin) who used plugin's other functions (see below)
public function getCountry()
{
global $wpdb;
$table_name = $wpdb->prefix . "country_wmu";
$results = $wpdb->get_results('SELECT * FROM ' . $table_name);
if ($wpdb->last_error !== '') {
echo '<p class="info-wmu error">Une erreur est survenue</p>';
} else {
return $results;
}
}
public function getLang($id)
{
global $wpdb;
$table_name = $wpdb->prefix . "lang_wmu";
$results = $wpdb->get_results('SELECT * FROM ' . $table_name . ' WHERE _id_country = ' . $id);
if ($wpdb->last_error !== '') {
echo '<p class="info-wmu error">Une erreur est survenue</p>';
} else {
return $results;
}
}
public function wmu_get_data($atts, $content=null)
{
$country = $this->getCountry();
foreach ($country as $key => $value) {
$country_id = $value->id;
$lang = $this->getLang($country_id);
foreach ($lang as $key2 => $value2) {
$country[$key]->lang = array(
'name' => $value2->name,
'url' => $value2->url
);
}
}
return $country;
}
and then add shortcode
add_shortcode('wmu_data', 'wmu_get_data');
and displaying the shortcode in the page, but shortcode displays as plain text
[wmu_data]
So I tried to do a function in my functions.php to do a do_shortcode, then add a shortcode to this function.
function test()
{
$country = do_shortcode('[wmu_data]');
echo '<pre>';
print_r($country);
echo '</pre>';
}
add_shortcode('test','test');
But nothing happens, blank page...
I really don't have many more ideas to do it...
EDIT:
I found out with the error code, Have to use
add_shortcode('wmu_data', array('WB_MultiLang_URL','wmu_data'));
to call it outside the function
thanks Larjos for pointing out the problem at his root :)

Header location doesn't work in my wordpress plugin.

I'm writing an Wordpress plugin. With this plugin I update some data. The query and updating works fine, but my header("location: url"); doesn't work. If I place an echo, it won't give any error that the headers already send. It looks it doesn't do anything with those lines. My code...
<?php require_once('../../../wp-config.php');
$baanstatus_table=$wpdb->prefix . 'baanstatus';
$id = $_GET['id'];
$bijgewerkt =$_GET['bijgewerkt'];
$baanstatus= $_GET['baanstatus'];
$handicarts = $_GET['handicarts'];
$trolleys = $_GET['trolleys'];
$winterontheffing = $_GET['winterontheffing'];
$zomergreens = $_GET['zomergreens'];
$qualifying = $_GET['qualifying'];
$onderhoud_greens = $_GET['onderhoud_greens'];
$onderhoud_anders = $_GET['onderhoud_anders'];
$opmerkingen = $_GET['opmerkingen'];
global $wpdb;
$data_array =array('id' => $id,
'bijgewerkt' => $bijgewerkt,
'baanstatus' => $baanstatus,
'handicarts' => $handicarts,
'trolleys' => $trolleys,
'winterontheffing' =>$winterontheffing,
'zomergreens' =>$zomergreens,
'qualifying' =>$qualifying,
'onderhoud_greens' =>$onderhoud_greens,
'onderhoud_anders' =>$onderhoud_anders,
'opmerkingen' =>$opmerkingen
);
$where =array('id' => $id);
$wpdb->update( $baanstatus_table, $data_array, $where );
header("location:http://almeerderhout.fcklap.com/wp-admin/options-general.php?page=my-unique-identifier");
exit();
?>
Perhaps you should try the javascript, instead of PHP location.
<?php
echo '<script>location.href="http://almeerderhout.fcklap.com/wp-admin/options-general.php?page=my-unique-identifier";</script>';
?>
The below code will help you
<?php
wp_redirect( $location, $status );
exit;
?>
The above wordpress function will use to redirect Codex Link function reference
You should hook your plugin to a proper Wordpress action to avoid the "headers already sent error" when trying to redirect.
I found that a good place to perform redirects is the template_redirect action, so you can write something like this:
function do_something_then_redirect() {
// do something with $_GET or $_POST data
// then redirect to some url defined in the $redirect_url variable
wp_redirect($redirect_url);
die;
}
add_action('template_redirect', 'do_something_then_redirect');

Wordpress Add custom permalink

I have a dynamic page setup in wordpress which uses a $_GET['id'] php variable to make a query to the database. The problem is that my url format looks like the following:
http://site.com/business/id?=123
What's the best way to make the url look like:
http://site.com/business/business-name-here
Is it done using rewrite rules in the .htaccess file?
Thanks in advance
I've found a great class to do just that by Kyle E try it.
<?php
/*
//Author Kyle E Gentile
//To use this class you must first include the file.
//After including the file, you need to create an options array. For example:
$options = array(
'query_vars' => array('var1', 'var2'),
'rules' => array('(.+?)/(.+?)/(.+?)/?$' => 'index.php?pagename=$matches[1]&var1=$matches[2]&var2=$matches[3]')
);
//After creating our $option array,
//we will need to create a new instance of the class as below:
$rewrite = new Add_rewrite_rules($options);
//You must pass the options array, this way. (If you don't there could be problems)
//Then you can call the filters and action functions as below:
add_action('wp_head', array(&$rewrite, 'flush_rules'));
add_action( 'generate_rewrite_rules', array(&$rewrite, 'add_rewrite_rules') );
add_filter( 'query_vars', array(&$rewrite, 'add_query_vars') );
//That is it.
*/
//prevent duplicate loading of the class if you are using this in multiply plugins
if(!class_exists('add_rewrite_rules')){
class Add_rewrite_rules{
var $query_vars;
var $rules;
function __construct($options){
$this->init($options);
}
function init($options){
foreach($options as $key => $value){
$this->$key = $value;
}
}
function rules_exist(){
global $wp_rewrite;
$has_rules = TRUE;
foreach($this->rules as $key => $value){
if(!in_array($value, $wp_rewrite->rules)){
$has_rules = FALSE;
}
}
return $has_rules;
}
//to be used add_action with the hook 'wp_head'
//flushing rewrite rules is labor intense so we better test to see if our rules exist first
//if the rules don't exist flush its like after a night of drinking
function flush_rules(){
global $wp_rewrite;
if(!$this->rules_exist()){
//echo "flushed"; // If want to see this in action uncomment this line and remove this text and you will see it flushed before your eyes
$wp_rewrite->flush_rules();
}
}
//filter function to be used with add_filter() with the hook "query_vars"
function add_query_vars($query_vars){
foreach($this->query_vars as $var){
$query_vars[] = $var;
}
return $query_vars;
}
//to be used with a the add_action() with the hook "generate_rewrite_rules"
function add_rewrite_rules(){
global $wp_rewrite;
$wp_rewrite->rules = $this->rules + $wp_rewrite->rules;
}
}
}
?>
Add the following function to the init of your plugin / functions file.
public function rewriteRules()
{
//Add the query variables to the list so wordpress doesn't discard them or worse use them to try and find by itself what page to serve.
$options = array(
'query_vars' => array('trainingid', 'vakname'),
'rules' =>
array( 'uncategorized/vak/([^/]+)/([^/]+)/?$' => 'index.php?p=1316&vakname=$matches[1]&level=$matches[2]'
)
);
//I use a autoloader but if you don't you have to include the class.
//include_once('path/to/AddRewriteRules.php');
$rewrite = new AddRewriteRules($options);
add_action('wp_head', array(&$rewrite, 'flush_rules'));
add_action('generate_rewrite_rules', array(&$rewrite, 'add_rewrite_rules'));
add_filter('query_vars', array(&$rewrite, 'add_query_vars'));
}

Wordpress how to prevent duplicate post by checking if post title exist before running "wp_insert_post"?

I have a wordpress site that connects to a soap server. The problem is every time I run the script the wp_insert_post is using the same result again.
I would like to check if existing post_title matches the value from $title then if they match, prevent wp_insert_post from using the same value again.
Here's the code:
try {
$client = new SoapClient($wsdl, array('login' => $username, 'password' => $password));
} catch(Exception $e) {
die('Couldn\'t establish connection to weblink service.');
}
$publications = $client->GetPublicationSummaries();
foreach ($publications->GetPublicationSummariesResult->PublicationSummaries->PublicationSummary as $publication_summary) {
// get the complete publication from the webservice
$publication = $client->getPublication(array('PublicationId' => $publication_summary->ID))->GetPublicationResult->Publication;
// get all properties and put them in an array
$properties = array();
foreach ($publication->Property as $attribute => $value) {
$properties[$attribute] = $value;
}
// Assemble basic title from properties
$title = $properties['Address']->Street . ' ' . $properties['Address']->HouseNumber . $properties['Address']->HouseNumberExtension . ', ' . $properties['Address']->City->_;
}
$my_post = array(
'post_title'=>$title,
'post_content'=>'my contents',
'post_status'=>'draft',
'post_type'=>'skarabeepublication',
'post_author'=>1,
);
wp_insert_post($my_post);
Thank you for any help.
You can use get_page_by_title() as it supports custom post types now.
if (!get_page_by_title($title, OBJECT, 'skarabeepublication')) :
$my_post = array(
'post_title'=>$title,
'post_content'=>'my contents',
'post_status'=>'draft',
'post_type'=>'skarabeepublication',
'post_author'=>1,
);
wp_insert_post($my_post);
endif;
Codex information here
Surprised not to see mention of post_exists function in wp-includes/post.php. See entry on wpseek. There is no entry in the codex. At it's simplest it works like get_page_by_title but returns a post id (or 0 if not found) instead of the object (or null).
$post_id = post_exists( $my_title );
if (!$post_id) {
// code here
}
Sorry for the late response. I used what Robot says in the comment and this solved my problem. Thanks
$post_if = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title like '$title_from_soap'");
if($post_if < 1){
//code here
}
sampler:
if( !get_page_by_path('mypageslug',OBJECT,'post') ){
//your codes
}

Resources