qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
354,689 | <p>I'm trying to handle the CF7 data before send and update the current post custom field using ACF function but I'm unable to get the current post ID the form is send from. I've also tried getting the ID from global $post variable and get_queried_object_id() but it didn't work either.</p>
<p>Any idea how can I get the ID of the post the form was send from?</p>
<pre><code>function dv_wpcf7_handle_form_data($wpcf7)
{
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$posted_data = $submission->get_posted_data();
}
// Check for ID of specific WPCF7 form
if ($wpcf7->id() == 128) {
$number_order = $posted_data['customer-number'];
$number_current_value = get_field('trip_available_seats', get_the_ID()); // passing the ID to function doesn't work
$number_new_value = $number_current_value - $number_order;
if ($number_new_value >= 0) {
update_field('trip_available_seats', $number_new_value, get_the_ID());
} else {
$error = true;
$err_msg = 'Error message...';
}
}
if (isset($error) && $error === true) {
$msgs = $wpcf7->prop('messages');
$msgs['mail_sent_ok'] = $err_msg;
$wpcf7->set_properties(array('messages' => $msgs));
add_filter('wpcf7_skip_mail', 'abort_mail_sending');
}
return $wpcf7;
}
add_action('wpcf7_before_send_mail', 'dv_wpcf7_handle_form_data');
function abort_mail_sending($contact_form)
{
return true;
}
</code></pre>
| [
{
"answer_id": 354694,
"author": "DesVal",
"author_id": 67802,
"author_profile": "https://wordpress.stackexchange.com/users/67802",
"pm_score": 2,
"selected": false,
"text": "<p>Found out you can get the container post ID with <code>$_POST['_wpcf7_container_post'])</code></p>\n"
},
{
"answer_id": 354695,
"author": "Awais",
"author_id": 141970,
"author_profile": "https://wordpress.stackexchange.com/users/141970",
"pm_score": 3,
"selected": false,
"text": "<p>You can get the post ID from array variable <code>$posted_data</code> the form was send from</p>\n<pre><code> if ($submission) {\n $posted_data = $submission->get_posted_data();\n print_r($posted_data)\n }\n</code></pre>\n<p>if you do a <code>print_r</code> on it you will get something like this:</p>\n<pre><code>Array\n(\n [_wpcf7] => 20\n [_wpcf7_version] => 5.1.6\n [_wpcf7_locale] => en_US\n [_wpcf7_unit_tag] => wpcf7-f20-p22-o1\n [_wpcf7_container_post] => 22 **//This is what you want.**\n [your-name] => Jon Doe\n [your-email] => [email protected]\n [your-subject] => subject\n [your-message] => message\n)\n</code></pre>\n<p>Edit:</p>\n<p>Since CF7 <strong>version 5.2</strong> the correct way to get the "<strong>post</strong>" ID to which the contact form is tied to is:</p>\n<pre><code>if ($submission) {\n print_r($_POST);\n}\n</code></pre>\n<p>That would return something like this:</p>\n<pre><code>Array\n(\n [_wpcf7] => 119 **//This is the "contact form" ID. But one should get that using WPCF7_ContactForm::get_current(); method **\n [_wpcf7_version] => 5.2.1\n [_wpcf7_locale] => en_US\n [_wpcf7_unit_tag] => wpcf7-f119-p120-o1\n [_wpcf7_container_post] => 120 **//This is the "post" ID**\n [_wpcf7_posted_data_hash] => \n [your-name] => Jon\n [your-email] => Doe\n [your-subject] => Test\n [your-message] => Test\n)\n</code></pre>\n"
},
{
"answer_id": 371310,
"author": "Pikamander2",
"author_id": 119995,
"author_profile": "https://wordpress.stackexchange.com/users/119995",
"pm_score": 3,
"selected": true,
"text": "<p>Due to <a href=\"https://wordpress.org/support/topic/critical-issue-with-5-2/#post-13138516\" rel=\"nofollow noreferrer\">a backwards-incompatible change</a> in version 5.2, you can no longer retrieve the form's meta data using <code>get_posted_data()</code>.</p>\n<p>Instead, you can use the <code>id</code> value in the array returned by <code>get_current()</code>:</p>\n<pre><code>$contact_form = WPCF7_ContactForm::get_current();\n$contact_form_id = $contact_form -> id;\n</code></pre>\n"
},
{
"answer_id": 375804,
"author": "matthias.wagner.wy",
"author_id": 180891,
"author_profile": "https://wordpress.stackexchange.com/users/180891",
"pm_score": 2,
"selected": false,
"text": "<p>if you prefer to retrieve the value from wpcf7 instead of the <code>$_POST</code> array, you can use the following. this is similar to how to retrieve the posted data. just use <code>get_meta</code> instead of <code>get_posted_data</code>:</p>\n<pre><code>$submission = WPCF7_Submission :: get_instance();\n$submission->get_meta('container_post_id');\n</code></pre>\n"
}
] | 2019/12/16 | [
"https://wordpress.stackexchange.com/questions/354689",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67802/"
] | I'm trying to handle the CF7 data before send and update the current post custom field using ACF function but I'm unable to get the current post ID the form is send from. I've also tried getting the ID from global $post variable and get\_queried\_object\_id() but it didn't work either.
Any idea how can I get the ID of the post the form was send from?
```
function dv_wpcf7_handle_form_data($wpcf7)
{
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$posted_data = $submission->get_posted_data();
}
// Check for ID of specific WPCF7 form
if ($wpcf7->id() == 128) {
$number_order = $posted_data['customer-number'];
$number_current_value = get_field('trip_available_seats', get_the_ID()); // passing the ID to function doesn't work
$number_new_value = $number_current_value - $number_order;
if ($number_new_value >= 0) {
update_field('trip_available_seats', $number_new_value, get_the_ID());
} else {
$error = true;
$err_msg = 'Error message...';
}
}
if (isset($error) && $error === true) {
$msgs = $wpcf7->prop('messages');
$msgs['mail_sent_ok'] = $err_msg;
$wpcf7->set_properties(array('messages' => $msgs));
add_filter('wpcf7_skip_mail', 'abort_mail_sending');
}
return $wpcf7;
}
add_action('wpcf7_before_send_mail', 'dv_wpcf7_handle_form_data');
function abort_mail_sending($contact_form)
{
return true;
}
``` | Due to [a backwards-incompatible change](https://wordpress.org/support/topic/critical-issue-with-5-2/#post-13138516) in version 5.2, you can no longer retrieve the form's meta data using `get_posted_data()`.
Instead, you can use the `id` value in the array returned by `get_current()`:
```
$contact_form = WPCF7_ContactForm::get_current();
$contact_form_id = $contact_form -> id;
``` |
354,728 | <p>I am trying to get a specific meta value from all of a customer's orders and simply echo them to the Downloads page within My Account. This is what I have so far, but unable to get $skey to retrieve and display the assigned values that are set from the backend. Basic idea is to go to a customer's order, define what we need for said order in the s_key custom field and just have that populate for customers just after their download links purchased. </p>
<p>Any help on this would be awesome! Certified php beginner so its possible I am doing something not quite right.</p>
<pre><code>function return_s_key_field() {
$args = array(
'customer_id' => $user_id);
$orders = wc_get_orders($args);
$skey = get_post_meta( $orders, 's_key', true );
echo ('<div id="request_title"></div>');
if ( empty($skey) == 'true' || $skey != 'N/A' ){
echo ('<div id="key_container"><div id="key_label"><p>Arbitrary text:</p></div><div id="steam_key"><p>' . $skey . '</p></div></div>');
}
else {
echo ('<div id="key_container"><div id="key_label"><p>Arbitrary text:</p></div><div id="steam_key"><p>N/A</p></div></div>');
}
}
add_action( 'woocommerce_after_available_downloads', 'return_s_key_field' );
</code></pre>
| [
{
"answer_id": 354749,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 0,
"selected": false,
"text": "<p>The problem with your code is that you're passing an array of orders, which <code>wc_get_orders()</code> to my knowledge returs but check WooC documentation, to <code>get_post_meta()</code>, which expects the first parameter to be an integer post ID. </p>\n\n<p>So modify your orders query to return only IDs, then loop that array through and on each iteration execute the <code>get_post_meta()</code> for that particular ID. Push the found meta data to a helper array variable and then use the data to do something after the loop has finished. </p>\n\n<pre><code>$order_ids = array(); // array of WooC order IDs\n$meta_data = array();\n\nforeach ($order_ids as $order_id) {\n $meta_data[$order_id] = get_post_meta($order_id, 's_key', true); \n}\n\nif ( $meta_data ) {\n // do something\n}\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_post_meta/</a></p>\n"
},
{
"answer_id": 354750,
"author": "Yatix",
"author_id": 8441,
"author_profile": "https://wordpress.stackexchange.com/users/8441",
"pm_score": 2,
"selected": true,
"text": "<p>Some basic issues with code. Since this hook do not have any data supplied to function, you need to get current user logged in. </p>\n\n<p>Secondly, as already mentioned by @antti, get_post_meta accepts first parameter as post id (in this case order id), single value. </p>\n\n<pre><code>function return_s_key_field() {\n\n$orders = wc_get_orders(array(\n 'customer_id' => get_current_user_id(),\n 'return' => 'ids',\n))\n\n$meta_data = array();\n\nforeach ($orders as $order_id) {\n $meta_data[$order_id] = get_post_meta($order_id, 's_key', true); \n}\n\n// var_dump($meta_data);\n\n}\nadd_action( 'woocommerce_after_available_downloads', 'return_s_key_field' );\n</code></pre>\n\n<p>Try un-commenting var_dump and then use that data however it is required.</p>\n"
}
] | 2019/12/16 | [
"https://wordpress.stackexchange.com/questions/354728",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148496/"
] | I am trying to get a specific meta value from all of a customer's orders and simply echo them to the Downloads page within My Account. This is what I have so far, but unable to get $skey to retrieve and display the assigned values that are set from the backend. Basic idea is to go to a customer's order, define what we need for said order in the s\_key custom field and just have that populate for customers just after their download links purchased.
Any help on this would be awesome! Certified php beginner so its possible I am doing something not quite right.
```
function return_s_key_field() {
$args = array(
'customer_id' => $user_id);
$orders = wc_get_orders($args);
$skey = get_post_meta( $orders, 's_key', true );
echo ('<div id="request_title"></div>');
if ( empty($skey) == 'true' || $skey != 'N/A' ){
echo ('<div id="key_container"><div id="key_label"><p>Arbitrary text:</p></div><div id="steam_key"><p>' . $skey . '</p></div></div>');
}
else {
echo ('<div id="key_container"><div id="key_label"><p>Arbitrary text:</p></div><div id="steam_key"><p>N/A</p></div></div>');
}
}
add_action( 'woocommerce_after_available_downloads', 'return_s_key_field' );
``` | Some basic issues with code. Since this hook do not have any data supplied to function, you need to get current user logged in.
Secondly, as already mentioned by @antti, get\_post\_meta accepts first parameter as post id (in this case order id), single value.
```
function return_s_key_field() {
$orders = wc_get_orders(array(
'customer_id' => get_current_user_id(),
'return' => 'ids',
))
$meta_data = array();
foreach ($orders as $order_id) {
$meta_data[$order_id] = get_post_meta($order_id, 's_key', true);
}
// var_dump($meta_data);
}
add_action( 'woocommerce_after_available_downloads', 'return_s_key_field' );
```
Try un-commenting var\_dump and then use that data however it is required. |
354,759 | <p>We're looking to add two new (custom post type) entries between Dashboard and Posts. </p>
<p>In this project, for the end user, two items are going to be <strong>by far</strong> the most used items in his dashboard. So we want them at the top.</p>
<p>These seem to be the built in <code>menu_position</code> settings:</p>
<p><a href="https://i.stack.imgur.com/2SOvX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2SOvX.png" alt="enter image description here"></a></p>
<p>This only gives a single slot, menu_position=<strong>3</strong>, between Dashboard and Posts. And we need <strong>two</strong> slots!</p>
<p>What we've tried:</p>
<p>1) Using decimals - as strings - is sometimes suggested (ie. 3.1 and 3.2). But this definitely doesn't work in current WordPress. Our menu entries drop down to the default position.</p>
<p>2) Setting both of them to 3. This isn't allowed. It results in one of them dropping down to the default position.</p>
<p>Other suggestions on this site involve a custom function which grabs <strong>all</strong> the menu items one by one and reorders them individually but this looks fragile. What if other items are added at a later date? Can't we just reorder Dashboard up (or Posts down) to make space?</p>
| [
{
"answer_id": 354779,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 3,
"selected": true,
"text": "<p>The order of the menu items can be changed using the filter <a href=\"https://developer.wordpress.org/reference/hooks/menu_order/\" rel=\"nofollow noreferrer\"><code>menu_order</code></a></p>\n\n<pre><code>add_filter( 'menu_order', 'se354759_menu_order' );\nadd_filter( 'custom_menu_order', '__return_true' );\n\nfunction se354759_menu_order ($menu_order)\n{\n $cpts = [\n 'edit.php?post_type=' . 'custom-post-type', \n 'edit.php?post_type=' . 'another-cpt'\n ];\n //\n // remove and save first item (\"dashboard\") in variable\n $first_item = array_shift( $menu_order );\n foreach( $cpts as $ctp )\n {\n $idx = array_search( $ctp, $menu_order );\n if ( $idx === false )\n continue;\n //\n // remove CPT menu item from array\n unset( $menu_order[$idx] );\n //\n // add CPT item to the beginning of the array\n array_unshift( $menu_order, $ctp );\n }\n //\n // re-add \"dashboard\" item\n array_unshift( $menu_order, $first_item );\n\n return $menu_order;\n}\n</code></pre>\n"
},
{
"answer_id": 413848,
"author": "RCNeil",
"author_id": 12294,
"author_profile": "https://wordpress.stackexchange.com/users/12294",
"pm_score": 0,
"selected": false,
"text": "<p>@nmr answer was incredibly helpful. For anyone who stumbles upon this, I also had an ACF options page fighting for order, as well. I modified the code to accommodate this by including the menu slug for the ACF options page:</p>\n<pre><code>if( function_exists('acf_add_options_page') ) { \n acf_add_options_page(array(\n 'page_title' => 'Site Settings',\n 'menu_title' => 'Site Settings',\n 'menu_slug' => 'my-ACF-slug'\n )); \n}\n</code></pre>\n<p>And then the filter modified:</p>\n<pre><code>add_filter( 'menu_order', 'se354759_menu_order' );\nadd_filter( 'custom_menu_order', '__return_true' );\n\nfunction se354759_menu_order ($menu_order) {\n $cpts = [\n 'edit.php?post_type=' . 'custom-post-type', \n 'edit.php?post_type=' . 'another-cpt',\n 'my-ACF-slug'\n ];\n\n $first_item = array_shift( $menu_order );\n foreach( $cpts as $ctp ) {\n $idx = array_search( $ctp, $menu_order );\n if ( $idx === false ) { continue; }\n unset( $menu_order[$idx] );\n array_unshift( $menu_order, $ctp );\n }\n array_unshift( $menu_order, $first_item );\n return $menu_order; \n }\n</code></pre>\n"
}
] | 2019/12/17 | [
"https://wordpress.stackexchange.com/questions/354759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/875/"
] | We're looking to add two new (custom post type) entries between Dashboard and Posts.
In this project, for the end user, two items are going to be **by far** the most used items in his dashboard. So we want them at the top.
These seem to be the built in `menu_position` settings:
[](https://i.stack.imgur.com/2SOvX.png)
This only gives a single slot, menu\_position=**3**, between Dashboard and Posts. And we need **two** slots!
What we've tried:
1) Using decimals - as strings - is sometimes suggested (ie. 3.1 and 3.2). But this definitely doesn't work in current WordPress. Our menu entries drop down to the default position.
2) Setting both of them to 3. This isn't allowed. It results in one of them dropping down to the default position.
Other suggestions on this site involve a custom function which grabs **all** the menu items one by one and reorders them individually but this looks fragile. What if other items are added at a later date? Can't we just reorder Dashboard up (or Posts down) to make space? | The order of the menu items can be changed using the filter [`menu_order`](https://developer.wordpress.org/reference/hooks/menu_order/)
```
add_filter( 'menu_order', 'se354759_menu_order' );
add_filter( 'custom_menu_order', '__return_true' );
function se354759_menu_order ($menu_order)
{
$cpts = [
'edit.php?post_type=' . 'custom-post-type',
'edit.php?post_type=' . 'another-cpt'
];
//
// remove and save first item ("dashboard") in variable
$first_item = array_shift( $menu_order );
foreach( $cpts as $ctp )
{
$idx = array_search( $ctp, $menu_order );
if ( $idx === false )
continue;
//
// remove CPT menu item from array
unset( $menu_order[$idx] );
//
// add CPT item to the beginning of the array
array_unshift( $menu_order, $ctp );
}
//
// re-add "dashboard" item
array_unshift( $menu_order, $first_item );
return $menu_order;
}
``` |
354,826 | <p>and thank you for any help you can provide. I've been trying to address this issue for a couple of days now, but I've found myself out of my depth... any help would be most appreciated--this is my first time trying to create a plugin, and I'm very new to PHP.</p>
<p>I have a custom plugin, cobbled together from Joshua David Nelson's <a href="https://joshuadnelson.com/weather-in-wordpress-with-forecast-io/" rel="nofollow noreferrer">Weather in Wordpress with DarkSky</a> article and <a href="https://www.youtube.com/watch?v=luXZFmQ70RA&list=PLylMDDjFIp1A2YqOnywaKLfoX2Tgvj5Q7&index=1" rel="nofollow noreferrer">this video series</a> from CodeTime. It works really well, except when I try to use the shortcode on a page twice (it is embedded in the menu, and trying to use the shortcode again on a page results in an error). I'm trying to display weather information in a different way on the homepage, and thought I could use the same sort of function/shortcode for it.</p>
<p>Here are the plugin contents, minus the coordinates and API key:</p>
<pre><code>function weather_station(){
$coordinates = 'XXXX'; //coordinates are here
$api_key = 'XXXX'; //api key is here
$api_url = 'https://api.darksky.net/forecast/'.$api_key.'/'.$coordinates;
$cache_key = md5( 'remote_request|' . $api_url );
$forecast_request = get_transient( $cache_key );
if ( false === $forecast_request ) {
$forecast_request = wp_remote_get( $api_url );
if ( is_wp_error( $forecast_request ) ) {
// Cache failures for a short time, will speed up page rendering in the event of remote failure.
set_transient( $cache_key, $forecast_request, 60 );
return false;
}
// Success, cache for a longer time.
set_transient( $cache_key, $forecast_request, 300 );
}
if ( is_wp_error( $forecast_request ) ) {
return false;
}
$body = wp_remote_retrieve_body( $forecast_request );
$forecast = json_decode( $body );
//$forecast = json_decode(file_get_contents($api_url));
$icon_currently = $forecast->currently->icon;
$temperature_currently = round( $forecast->currently->temperature );
$summary_hourly = $forecast->hourly->summary;
// Set the default timezone
date_default_timezone_set($forecast->timezone);
// Get the appropriate icon
function get_icon($icon) {
if($icon==='clear-day') {
$the_icon = '<i class="fas fa-sun"></i>';
return $the_icon;
}
elseif($icon==='clear-night') {
$the_icon = '<i class="fas fa-moon-stars"></i>';
return $the_icon;
}
elseif($icon==='rain') {
$the_icon = '<i class="fas fa-cloud-showers-heavy"></i>';
return $the_icon;
}
elseif($icon==='snow') {
$the_icon = '<i class="fas fa-cloud-snow"></i>';
return $the_icon;
}
elseif($icon==='sleet') {
$the_icon = '<i class="fas fa-cloud-sleet"></i>';
return $the_icon;
}
elseif($icon==='wind') {
$the_icon = '<i class="fas fa-wind"></i>';
return $the_icon;
}
elseif($icon==='fog') {
$the_icon = '<i class="fas fa-fog"></i>';
return $the_icon;
}
elseif($icon==='cloudy') {
$the_icon = '<i class="fas fa-clouds"></i>';
return $the_icon;
}
elseif($icon==='partly-cloudy-day') {
$the_icon = '<i class="fas fa-clouds-sun"></i>';
return $the_icon;
}
elseif($icon==='partly-cloudy-night') {
$the_icon = '<i class="fas fa-clouds-moon"></i>';
return $the_icon;
}
elseif($icon==='hail') {
$the_icon = '<i class="fas fa-cloud-hail"></i>';
return $the_icon;
}
elseif($icon==='thunderstorm') {
$the_icon = '<i class="fas fa-thunderstorm"></i>';
return $the_icon;
}
elseif($icon==='tornado') {
$the_icon = '<i class="fas fa-tornado"></i>';
return $the_icon;
}
else {
$the_icon = '<i class="fas fa-thermometer-half"></i>';
return $the_icon;
}
}
?>
<div class="weather-station">
<div class="weather-station-button">
<span class="weather-station-icon"><?php echo get_icon($forecast->currently->icon) ?></span>
<span class="weather-station-temperature-currently"><?php echo $temperature_currently ?>&deg;</span>
</div>
<div class="weather-station-details">
<p class="weather-station-details-title">Forecast</p>
<?php
// Start the foreach loop to get hourly forecast
foreach($forecast->daily->data as $day):
?>
<p class="weather-station-details-temperature-range"><?php echo round($day->temperatureLow).'&deg;/'.round($day->temperatureHigh).'&deg;'; ?></p>
<?php
// Break because we got today's low/high
break;
// End the foreach loop
endforeach;
?>
<p class="weather-station-details-summary"><?php echo $summary_hourly ?></p>
<?php if (!empty($forecast->alerts)) { ?>
<ul class="weather-station-details-alerts">
<?php
// Start the foreach loop to get hourly forecast
foreach($forecast->alerts as $alert):
?>
<li><a href="<?php echo $alert->uri ?>"><?php echo $alert->title ?></a><br><span>expires <?php echo date("g:i a", $alert->expires) ?></span></li>
<?php
// End the foreach loop
endforeach;
?>
</ul>
<?php } ?>
<p class="weather-station-details-darksky"><a href="https://darksky.net/poweredby/" target="_blank">Powered by Dark Sky</a></p>
</div>
</div>
<?php }
add_shortcode('go_weather_station', 'weather_station');
</code></pre>
<p>I turned on wp_debug, and it shows me where the issue is--I'm just not sure of the best way to fix it. The error message is:</p>
<blockquote>
<p>Fatal error: Cannot redeclare get_icon() (previously declared in
/www/wp-content/plugins/go-weather/go-weather.php:52) in
/www/wp-content/plugins/go-weather/go-weather.php on line 52</p>
</blockquote>
<p>I've since read that I should not declare a function within a function, which I'm doing at line 52, but I have tried moving it to no avail (the plugin doesn't seem to work at all). I'd be grateful for any tips; I'll be working to solve the issue myself as well, but if anyone is willing to give me a boost, that would be amazing. Thanks very much.</p>
| [
{
"answer_id": 354836,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 3,
"selected": true,
"text": "<p>As @TomJNowell said, You must never nest functions like that. so First,you have to move that functions out of that shortcode function and paste separately in your plugin's file or active themes functions.php file. Second, follow what the codex says <a href=\"https://codex.wordpress.org/Shortcode_API#Output\" rel=\"nofollow noreferrer\">Shortcodes</a>, If the shortcode produces a lot of HTML then <code>ob_start</code> can be used to capture output and convert it to a string. I have tested using two shortcode in page and it is working fine <a href=\"https://prnt.sc/qceew0\" rel=\"nofollow noreferrer\">https://prnt.sc/qceew0</a></p>\n\n<pre><code>function weather_station(){\n ob_start();\n $coordinates = 'XXXX'; //coordinates are here\n $api_key = 'XXXXXX'; //api key is here\n $api_url = 'https://api.darksky.net/forecast/'.$api_key.'/'.$coordinates;\n $cache_key = md5( 'remote_request|' . $api_url );\n $forecast_request = get_transient( $cache_key );\n\n if ( false === $forecast_request ) {\n $forecast_request = wp_remote_get( $api_url );\n if ( is_wp_error( $forecast_request ) ) {\n // Cache failures for a short time, will speed up page rendering in the event of remote failure.\n set_transient( $cache_key, $forecast_request, 60 );\n return false;\n }\n // Success, cache for a longer time.\n set_transient( $cache_key, $forecast_request, 300 );\n }\n\n if ( is_wp_error( $forecast_request ) ) {\n return false;\n }\n $body = wp_remote_retrieve_body( $forecast_request );\n $forecast = json_decode( $body );\n //$forecast = json_decode(file_get_contents($api_url));\n\n $icon_currently = $forecast->currently->icon;\n $temperature_currently = round( $forecast->currently->temperature );\n $summary_hourly = $forecast->hourly->summary;\n\n // Set the default timezone\n date_default_timezone_set($forecast->timezone);\n\n ?>\n <div class=\"weather-station\">\n <div class=\"weather-station-button\">\n <span class=\"weather-station-icon\"><?php echo get_icon($forecast->currently->icon) ?></span>\n <span class=\"weather-station-temperature-currently\"><?php echo $temperature_currently ?>&deg;</span>\n </div>\n <div class=\"weather-station-details\">\n <p class=\"weather-station-details-title\">Forecast</p>\n <?php\n // Start the foreach loop to get hourly forecast\n foreach($forecast->daily->data as $day):\n ?>\n\n <p class=\"weather-station-details-temperature-range\"><?php echo round($day->temperatureLow).'&deg;/'.round($day->temperatureHigh).'&deg;'; ?></p>\n <?php\n // Break because we got today's low/high\n break;\n // End the foreach loop\n endforeach;\n ?>\n <p class=\"weather-station-details-summary\"><?php echo $summary_hourly ?></p>\n <?php if (!empty($forecast->alerts)) { ?>\n <ul class=\"weather-station-details-alerts\">\n <?php\n // Start the foreach loop to get hourly forecast\n foreach($forecast->alerts as $alert):\n ?>\n <li><a href=\"<?php echo $alert->uri ?>\"><?php echo $alert->title ?></a><br><span>expires <?php echo date(\"g:i a\", $alert->expires) ?></span></li>\n <?php\n // End the foreach loop\n endforeach;\n ?>\n </ul>\n <?php } ?>\n <p class=\"weather-station-details-darksky\"><a href=\"https://darksky.net/poweredby/\" target=\"_blank\">Powered by Dark Sky</a></p>\n </div>\n </div>\n <?php \n return ob_get_clean();\n}\nadd_shortcode('go_weather_station', 'weather_station');\n\n// Get the appropriate icon\nfunction get_icon($icon) {\n if($icon==='clear-day') {\n $the_icon = '<i class=\"fas fa-sun\"></i>';\n return $the_icon;\n }\n elseif($icon==='clear-night') {\n $the_icon = '<i class=\"fas fa-moon-stars\"></i>';\n return $the_icon;\n }\n elseif($icon==='rain') {\n $the_icon = '<i class=\"fas fa-cloud-showers-heavy\"></i>';\n return $the_icon;\n }\n elseif($icon==='snow') {\n $the_icon = '<i class=\"fas fa-cloud-snow\"></i>';\n return $the_icon;\n }\n elseif($icon==='sleet') {\n $the_icon = '<i class=\"fas fa-cloud-sleet\"></i>';\n return $the_icon;\n }\n elseif($icon==='wind') {\n $the_icon = '<i class=\"fas fa-wind\"></i>';\n return $the_icon;\n }\n elseif($icon==='fog') {\n $the_icon = '<i class=\"fas fa-fog\"></i>';\n return $the_icon;\n }\n elseif($icon==='cloudy') {\n $the_icon = '<i class=\"fas fa-clouds\"></i>';\n return $the_icon;\n }\n elseif($icon==='partly-cloudy-day') {\n $the_icon = '<i class=\"fas fa-clouds-sun\"></i>';\n return $the_icon;\n }\n elseif($icon==='partly-cloudy-night') {\n $the_icon = '<i class=\"fas fa-clouds-moon\"></i>';\n return $the_icon;\n }\n elseif($icon==='hail') {\n $the_icon = '<i class=\"fas fa-cloud-hail\"></i>';\n return $the_icon;\n }\n elseif($icon==='thunderstorm') {\n $the_icon = '<i class=\"fas fa-thunderstorm\"></i>';\n return $the_icon;\n }\n elseif($icon==='tornado') {\n $the_icon = '<i class=\"fas fa-tornado\"></i>';\n return $the_icon;\n }\n else {\n $the_icon = '<i class=\"fas fa-thermometer-half\"></i>';\n return $the_icon;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 354846,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 0,
"selected": false,
"text": "<p>you can factorise the \"get_icon\" function like that</p>\n\n<pre><code>function get_icon($icon) {\n\n $names = [\n \"clear-day\" => \"sun\",\n \"clear-night\" => \"moon-stars\",\n \"rain\" => \"cloud-showers-heavy\",\n \"snow\" => \"cloud-snow\",\n \"sleet\" => \"cloud-sleet\",\n \"wind\" => \"wind\",\n \"fog\" => \"fog\",\n \"cloudy\" => \"clouds\",\n \"partly-cloudy-day\" => \"clouds-sun\",\n \"partly-cloudy-night\" => \"clouds-moon\",\n \"hail\" => \"cloud-hail\",\n \"thunderstorm\" => \"thunderstorm\",\n \"tornado\" => \"tornado\",\n ];\n\n $value = $names[$icon] ?? \"thermometer-half\";\n\n\n return \"<i class=\\\"fas fa-{$value}\\\"></i>\";\n\n}\n</code></pre>\n"
}
] | 2019/12/17 | [
"https://wordpress.stackexchange.com/questions/354826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179903/"
] | and thank you for any help you can provide. I've been trying to address this issue for a couple of days now, but I've found myself out of my depth... any help would be most appreciated--this is my first time trying to create a plugin, and I'm very new to PHP.
I have a custom plugin, cobbled together from Joshua David Nelson's [Weather in Wordpress with DarkSky](https://joshuadnelson.com/weather-in-wordpress-with-forecast-io/) article and [this video series](https://www.youtube.com/watch?v=luXZFmQ70RA&list=PLylMDDjFIp1A2YqOnywaKLfoX2Tgvj5Q7&index=1) from CodeTime. It works really well, except when I try to use the shortcode on a page twice (it is embedded in the menu, and trying to use the shortcode again on a page results in an error). I'm trying to display weather information in a different way on the homepage, and thought I could use the same sort of function/shortcode for it.
Here are the plugin contents, minus the coordinates and API key:
```
function weather_station(){
$coordinates = 'XXXX'; //coordinates are here
$api_key = 'XXXX'; //api key is here
$api_url = 'https://api.darksky.net/forecast/'.$api_key.'/'.$coordinates;
$cache_key = md5( 'remote_request|' . $api_url );
$forecast_request = get_transient( $cache_key );
if ( false === $forecast_request ) {
$forecast_request = wp_remote_get( $api_url );
if ( is_wp_error( $forecast_request ) ) {
// Cache failures for a short time, will speed up page rendering in the event of remote failure.
set_transient( $cache_key, $forecast_request, 60 );
return false;
}
// Success, cache for a longer time.
set_transient( $cache_key, $forecast_request, 300 );
}
if ( is_wp_error( $forecast_request ) ) {
return false;
}
$body = wp_remote_retrieve_body( $forecast_request );
$forecast = json_decode( $body );
//$forecast = json_decode(file_get_contents($api_url));
$icon_currently = $forecast->currently->icon;
$temperature_currently = round( $forecast->currently->temperature );
$summary_hourly = $forecast->hourly->summary;
// Set the default timezone
date_default_timezone_set($forecast->timezone);
// Get the appropriate icon
function get_icon($icon) {
if($icon==='clear-day') {
$the_icon = '<i class="fas fa-sun"></i>';
return $the_icon;
}
elseif($icon==='clear-night') {
$the_icon = '<i class="fas fa-moon-stars"></i>';
return $the_icon;
}
elseif($icon==='rain') {
$the_icon = '<i class="fas fa-cloud-showers-heavy"></i>';
return $the_icon;
}
elseif($icon==='snow') {
$the_icon = '<i class="fas fa-cloud-snow"></i>';
return $the_icon;
}
elseif($icon==='sleet') {
$the_icon = '<i class="fas fa-cloud-sleet"></i>';
return $the_icon;
}
elseif($icon==='wind') {
$the_icon = '<i class="fas fa-wind"></i>';
return $the_icon;
}
elseif($icon==='fog') {
$the_icon = '<i class="fas fa-fog"></i>';
return $the_icon;
}
elseif($icon==='cloudy') {
$the_icon = '<i class="fas fa-clouds"></i>';
return $the_icon;
}
elseif($icon==='partly-cloudy-day') {
$the_icon = '<i class="fas fa-clouds-sun"></i>';
return $the_icon;
}
elseif($icon==='partly-cloudy-night') {
$the_icon = '<i class="fas fa-clouds-moon"></i>';
return $the_icon;
}
elseif($icon==='hail') {
$the_icon = '<i class="fas fa-cloud-hail"></i>';
return $the_icon;
}
elseif($icon==='thunderstorm') {
$the_icon = '<i class="fas fa-thunderstorm"></i>';
return $the_icon;
}
elseif($icon==='tornado') {
$the_icon = '<i class="fas fa-tornado"></i>';
return $the_icon;
}
else {
$the_icon = '<i class="fas fa-thermometer-half"></i>';
return $the_icon;
}
}
?>
<div class="weather-station">
<div class="weather-station-button">
<span class="weather-station-icon"><?php echo get_icon($forecast->currently->icon) ?></span>
<span class="weather-station-temperature-currently"><?php echo $temperature_currently ?>°</span>
</div>
<div class="weather-station-details">
<p class="weather-station-details-title">Forecast</p>
<?php
// Start the foreach loop to get hourly forecast
foreach($forecast->daily->data as $day):
?>
<p class="weather-station-details-temperature-range"><?php echo round($day->temperatureLow).'°/'.round($day->temperatureHigh).'°'; ?></p>
<?php
// Break because we got today's low/high
break;
// End the foreach loop
endforeach;
?>
<p class="weather-station-details-summary"><?php echo $summary_hourly ?></p>
<?php if (!empty($forecast->alerts)) { ?>
<ul class="weather-station-details-alerts">
<?php
// Start the foreach loop to get hourly forecast
foreach($forecast->alerts as $alert):
?>
<li><a href="<?php echo $alert->uri ?>"><?php echo $alert->title ?></a><br><span>expires <?php echo date("g:i a", $alert->expires) ?></span></li>
<?php
// End the foreach loop
endforeach;
?>
</ul>
<?php } ?>
<p class="weather-station-details-darksky"><a href="https://darksky.net/poweredby/" target="_blank">Powered by Dark Sky</a></p>
</div>
</div>
<?php }
add_shortcode('go_weather_station', 'weather_station');
```
I turned on wp\_debug, and it shows me where the issue is--I'm just not sure of the best way to fix it. The error message is:
>
> Fatal error: Cannot redeclare get\_icon() (previously declared in
> /www/wp-content/plugins/go-weather/go-weather.php:52) in
> /www/wp-content/plugins/go-weather/go-weather.php on line 52
>
>
>
I've since read that I should not declare a function within a function, which I'm doing at line 52, but I have tried moving it to no avail (the plugin doesn't seem to work at all). I'd be grateful for any tips; I'll be working to solve the issue myself as well, but if anyone is willing to give me a boost, that would be amazing. Thanks very much. | As @TomJNowell said, You must never nest functions like that. so First,you have to move that functions out of that shortcode function and paste separately in your plugin's file or active themes functions.php file. Second, follow what the codex says [Shortcodes](https://codex.wordpress.org/Shortcode_API#Output), If the shortcode produces a lot of HTML then `ob_start` can be used to capture output and convert it to a string. I have tested using two shortcode in page and it is working fine <https://prnt.sc/qceew0>
```
function weather_station(){
ob_start();
$coordinates = 'XXXX'; //coordinates are here
$api_key = 'XXXXXX'; //api key is here
$api_url = 'https://api.darksky.net/forecast/'.$api_key.'/'.$coordinates;
$cache_key = md5( 'remote_request|' . $api_url );
$forecast_request = get_transient( $cache_key );
if ( false === $forecast_request ) {
$forecast_request = wp_remote_get( $api_url );
if ( is_wp_error( $forecast_request ) ) {
// Cache failures for a short time, will speed up page rendering in the event of remote failure.
set_transient( $cache_key, $forecast_request, 60 );
return false;
}
// Success, cache for a longer time.
set_transient( $cache_key, $forecast_request, 300 );
}
if ( is_wp_error( $forecast_request ) ) {
return false;
}
$body = wp_remote_retrieve_body( $forecast_request );
$forecast = json_decode( $body );
//$forecast = json_decode(file_get_contents($api_url));
$icon_currently = $forecast->currently->icon;
$temperature_currently = round( $forecast->currently->temperature );
$summary_hourly = $forecast->hourly->summary;
// Set the default timezone
date_default_timezone_set($forecast->timezone);
?>
<div class="weather-station">
<div class="weather-station-button">
<span class="weather-station-icon"><?php echo get_icon($forecast->currently->icon) ?></span>
<span class="weather-station-temperature-currently"><?php echo $temperature_currently ?>°</span>
</div>
<div class="weather-station-details">
<p class="weather-station-details-title">Forecast</p>
<?php
// Start the foreach loop to get hourly forecast
foreach($forecast->daily->data as $day):
?>
<p class="weather-station-details-temperature-range"><?php echo round($day->temperatureLow).'°/'.round($day->temperatureHigh).'°'; ?></p>
<?php
// Break because we got today's low/high
break;
// End the foreach loop
endforeach;
?>
<p class="weather-station-details-summary"><?php echo $summary_hourly ?></p>
<?php if (!empty($forecast->alerts)) { ?>
<ul class="weather-station-details-alerts">
<?php
// Start the foreach loop to get hourly forecast
foreach($forecast->alerts as $alert):
?>
<li><a href="<?php echo $alert->uri ?>"><?php echo $alert->title ?></a><br><span>expires <?php echo date("g:i a", $alert->expires) ?></span></li>
<?php
// End the foreach loop
endforeach;
?>
</ul>
<?php } ?>
<p class="weather-station-details-darksky"><a href="https://darksky.net/poweredby/" target="_blank">Powered by Dark Sky</a></p>
</div>
</div>
<?php
return ob_get_clean();
}
add_shortcode('go_weather_station', 'weather_station');
// Get the appropriate icon
function get_icon($icon) {
if($icon==='clear-day') {
$the_icon = '<i class="fas fa-sun"></i>';
return $the_icon;
}
elseif($icon==='clear-night') {
$the_icon = '<i class="fas fa-moon-stars"></i>';
return $the_icon;
}
elseif($icon==='rain') {
$the_icon = '<i class="fas fa-cloud-showers-heavy"></i>';
return $the_icon;
}
elseif($icon==='snow') {
$the_icon = '<i class="fas fa-cloud-snow"></i>';
return $the_icon;
}
elseif($icon==='sleet') {
$the_icon = '<i class="fas fa-cloud-sleet"></i>';
return $the_icon;
}
elseif($icon==='wind') {
$the_icon = '<i class="fas fa-wind"></i>';
return $the_icon;
}
elseif($icon==='fog') {
$the_icon = '<i class="fas fa-fog"></i>';
return $the_icon;
}
elseif($icon==='cloudy') {
$the_icon = '<i class="fas fa-clouds"></i>';
return $the_icon;
}
elseif($icon==='partly-cloudy-day') {
$the_icon = '<i class="fas fa-clouds-sun"></i>';
return $the_icon;
}
elseif($icon==='partly-cloudy-night') {
$the_icon = '<i class="fas fa-clouds-moon"></i>';
return $the_icon;
}
elseif($icon==='hail') {
$the_icon = '<i class="fas fa-cloud-hail"></i>';
return $the_icon;
}
elseif($icon==='thunderstorm') {
$the_icon = '<i class="fas fa-thunderstorm"></i>';
return $the_icon;
}
elseif($icon==='tornado') {
$the_icon = '<i class="fas fa-tornado"></i>';
return $the_icon;
}
else {
$the_icon = '<i class="fas fa-thermometer-half"></i>';
return $the_icon;
}
}
``` |
354,847 | <p>In one of my client sites, the default comment feature is not needed globally. Instead I'm using it only under a certain CPT (eg. Complaints). With the following code, I moved the parent menu item: "Comments" under the "Complaints" CPT:</p>
<pre><code><?php
/**
* Relocate Comments in Admin Menu.
*
* Relocate Comments parent menu under a CPT.
*/
function wpse354847_relocate_comments_in_admin_menu()
{
// Remove existing parent menu.
remove_menu_page( 'edit-comments.php' );
// Move Comments under Complaints ('complaint').
add_submenu_page(
'edit.php?post_type=complaint', //$parent_slug
__( 'Replies', 'wpse354847' ), //$page_title
__( 'Replies', 'wpse354847' ), //$menu_title
'edit_posts', //$capability
'edit-comments.php' //$menu_slug
);
}
add_action( 'admin_menu', 'wpse354847_relocate_comments_in_admin_menu' );
</code></pre>
<p>But the issue is: when I'm on the "Comments" page the parent menu is not get selected. I found that, two HTML classes are responsible for the CSS to be triggered: <code>.wp-has-current-submenu</code> and <code>.wp-menu-open</code>.</p>
<h3>Desired output</h3>
<p><a href="https://i.stack.imgur.com/2RUJP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2RUJP.png" alt="Desired output with Main menu active"></a></p>
<h3>Current output</h3>
<p><a href="https://i.stack.imgur.com/NLk2y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NLk2y.png" alt="Current output with no trace of current page in admin menu"></a></p>
<p>After some searching I found some Javascript approaches to resolve the issue - like:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/a/225228/22728"><strong>Moving Categories submenu to Media, but still opens Posts menu</strong> - WPSE</a></li>
<li><a href="https://stackoverflow.com/a/23548730/1743124"><strong>How to manually set a custom admin submenu selected?</strong> - WPSE</a></li>
</ul>
<p>But I'm not convinced with them, as I might be wrong when I'm repositioning the Comments menu page as a submenu where the native active menu classes are not loading.</p>
<p>Hence I'm asking here: am I on the right track? Is Javascript the only last resort to solve the issue?</p>
| [
{
"answer_id": 354852,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 1,
"selected": false,
"text": "<p>the first step is to set <code>edit-comments.php?post_type=complaint</code> for the menu slug.</p>\n\n<p>and then you add this hook</p>\n\n<pre><code>add_filter(\"submenu_file\", function ($submenu_file, $parent_file) {\n\n $screen = get_current_screen();\n\n if (\"edit-comments\" === $screen->id) {\n $submenu_file = \"edit-comments.php?post_type=$screen->post_type\";\n }\n\n return $submenu_file;\n\n}, 10, 2);\n</code></pre>\n"
},
{
"answer_id": 354854,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 3,
"selected": true,
"text": "<p>By adding <code>post_type</code> to <code>add_submenu_page</code> menu slug it will active CPT page menu. then you have to add parent page as that CPT to that commnet page by using <code>submenu_file</code> filter.</p>\n\n<p><strong># Move comment to CPT</strong></p>\n\n<pre><code>function wpse354847_relocate_comments_in_admin_menu()\n{\n // Remove existing parent menu.\n remove_menu_page( 'edit-comments.php' );\n\n // Move Comments under Complaints ('complaint').\n add_submenu_page(\n 'edit.php?post_type=complaint', //$parent_slug\n __( 'Replies', 'wpse354847' ), //$page_title\n __( 'Replies', 'wpse354847' ), //$menu_title\n 'edit_posts', //$capability\n 'edit-comments.php?post_type=complaint' //$menu_slug\n );\n}\nadd_action( 'admin_menu', 'wpse354847_relocate_comments_in_admin_menu' );\n</code></pre>\n\n<p><strong># add active page for parent page</strong></p>\n\n<pre><code>add_filter('submenu_file', 'menuBold');\nfunction menuBold($submenu_file)\n{\n global $pagenow;\n if (( $pagenow == 'edit-comments.php' ) && ($_GET['post_type'] == 'complaint')) { // The address of the link to be highlighted\n return 'edit-comments.php?post_type=complaint';\n }\n // Don't change anything\n return $submenu_file;\n}\n</code></pre>\n"
}
] | 2019/12/18 | [
"https://wordpress.stackexchange.com/questions/354847",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22728/"
] | In one of my client sites, the default comment feature is not needed globally. Instead I'm using it only under a certain CPT (eg. Complaints). With the following code, I moved the parent menu item: "Comments" under the "Complaints" CPT:
```
<?php
/**
* Relocate Comments in Admin Menu.
*
* Relocate Comments parent menu under a CPT.
*/
function wpse354847_relocate_comments_in_admin_menu()
{
// Remove existing parent menu.
remove_menu_page( 'edit-comments.php' );
// Move Comments under Complaints ('complaint').
add_submenu_page(
'edit.php?post_type=complaint', //$parent_slug
__( 'Replies', 'wpse354847' ), //$page_title
__( 'Replies', 'wpse354847' ), //$menu_title
'edit_posts', //$capability
'edit-comments.php' //$menu_slug
);
}
add_action( 'admin_menu', 'wpse354847_relocate_comments_in_admin_menu' );
```
But the issue is: when I'm on the "Comments" page the parent menu is not get selected. I found that, two HTML classes are responsible for the CSS to be triggered: `.wp-has-current-submenu` and `.wp-menu-open`.
### Desired output
[](https://i.stack.imgur.com/2RUJP.png)
### Current output
[](https://i.stack.imgur.com/NLk2y.png)
After some searching I found some Javascript approaches to resolve the issue - like:
* [**Moving Categories submenu to Media, but still opens Posts menu** - WPSE](https://wordpress.stackexchange.com/a/225228/22728)
* [**How to manually set a custom admin submenu selected?** - WPSE](https://stackoverflow.com/a/23548730/1743124)
But I'm not convinced with them, as I might be wrong when I'm repositioning the Comments menu page as a submenu where the native active menu classes are not loading.
Hence I'm asking here: am I on the right track? Is Javascript the only last resort to solve the issue? | By adding `post_type` to `add_submenu_page` menu slug it will active CPT page menu. then you have to add parent page as that CPT to that commnet page by using `submenu_file` filter.
**# Move comment to CPT**
```
function wpse354847_relocate_comments_in_admin_menu()
{
// Remove existing parent menu.
remove_menu_page( 'edit-comments.php' );
// Move Comments under Complaints ('complaint').
add_submenu_page(
'edit.php?post_type=complaint', //$parent_slug
__( 'Replies', 'wpse354847' ), //$page_title
__( 'Replies', 'wpse354847' ), //$menu_title
'edit_posts', //$capability
'edit-comments.php?post_type=complaint' //$menu_slug
);
}
add_action( 'admin_menu', 'wpse354847_relocate_comments_in_admin_menu' );
```
**# add active page for parent page**
```
add_filter('submenu_file', 'menuBold');
function menuBold($submenu_file)
{
global $pagenow;
if (( $pagenow == 'edit-comments.php' ) && ($_GET['post_type'] == 'complaint')) { // The address of the link to be highlighted
return 'edit-comments.php?post_type=complaint';
}
// Don't change anything
return $submenu_file;
}
``` |
354,857 | <p>I have wordPress site. My website works under demo directory. URL looks like this www.website.com/demo. I want change that to normal like www.website.com how to do that please help. Thank you</p>
| [
{
"answer_id": 354852,
"author": "Kaperto",
"author_id": 147795,
"author_profile": "https://wordpress.stackexchange.com/users/147795",
"pm_score": 1,
"selected": false,
"text": "<p>the first step is to set <code>edit-comments.php?post_type=complaint</code> for the menu slug.</p>\n\n<p>and then you add this hook</p>\n\n<pre><code>add_filter(\"submenu_file\", function ($submenu_file, $parent_file) {\n\n $screen = get_current_screen();\n\n if (\"edit-comments\" === $screen->id) {\n $submenu_file = \"edit-comments.php?post_type=$screen->post_type\";\n }\n\n return $submenu_file;\n\n}, 10, 2);\n</code></pre>\n"
},
{
"answer_id": 354854,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 3,
"selected": true,
"text": "<p>By adding <code>post_type</code> to <code>add_submenu_page</code> menu slug it will active CPT page menu. then you have to add parent page as that CPT to that commnet page by using <code>submenu_file</code> filter.</p>\n\n<p><strong># Move comment to CPT</strong></p>\n\n<pre><code>function wpse354847_relocate_comments_in_admin_menu()\n{\n // Remove existing parent menu.\n remove_menu_page( 'edit-comments.php' );\n\n // Move Comments under Complaints ('complaint').\n add_submenu_page(\n 'edit.php?post_type=complaint', //$parent_slug\n __( 'Replies', 'wpse354847' ), //$page_title\n __( 'Replies', 'wpse354847' ), //$menu_title\n 'edit_posts', //$capability\n 'edit-comments.php?post_type=complaint' //$menu_slug\n );\n}\nadd_action( 'admin_menu', 'wpse354847_relocate_comments_in_admin_menu' );\n</code></pre>\n\n<p><strong># add active page for parent page</strong></p>\n\n<pre><code>add_filter('submenu_file', 'menuBold');\nfunction menuBold($submenu_file)\n{\n global $pagenow;\n if (( $pagenow == 'edit-comments.php' ) && ($_GET['post_type'] == 'complaint')) { // The address of the link to be highlighted\n return 'edit-comments.php?post_type=complaint';\n }\n // Don't change anything\n return $submenu_file;\n}\n</code></pre>\n"
}
] | 2019/12/18 | [
"https://wordpress.stackexchange.com/questions/354857",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179933/"
] | I have wordPress site. My website works under demo directory. URL looks like this www.website.com/demo. I want change that to normal like www.website.com how to do that please help. Thank you | By adding `post_type` to `add_submenu_page` menu slug it will active CPT page menu. then you have to add parent page as that CPT to that commnet page by using `submenu_file` filter.
**# Move comment to CPT**
```
function wpse354847_relocate_comments_in_admin_menu()
{
// Remove existing parent menu.
remove_menu_page( 'edit-comments.php' );
// Move Comments under Complaints ('complaint').
add_submenu_page(
'edit.php?post_type=complaint', //$parent_slug
__( 'Replies', 'wpse354847' ), //$page_title
__( 'Replies', 'wpse354847' ), //$menu_title
'edit_posts', //$capability
'edit-comments.php?post_type=complaint' //$menu_slug
);
}
add_action( 'admin_menu', 'wpse354847_relocate_comments_in_admin_menu' );
```
**# add active page for parent page**
```
add_filter('submenu_file', 'menuBold');
function menuBold($submenu_file)
{
global $pagenow;
if (( $pagenow == 'edit-comments.php' ) && ($_GET['post_type'] == 'complaint')) { // The address of the link to be highlighted
return 'edit-comments.php?post_type=complaint';
}
// Don't change anything
return $submenu_file;
}
``` |
354,875 | <p>I would like to have 3 editable columns (25, 50, 25) like you can insert in Gutenberg, per default in every new page. How can I do this? If I give the columns to <code>page.php</code> they are not editable.</p>
| [
{
"answer_id": 354948,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 3,
"selected": true,
"text": "<p>So first of all this is <a href=\"https://developer.wordpress.org/block-editor/developers/block-api/block-templates/\" rel=\"nofollow noreferrer\">explained in detail in the documentation</a>, just not exactly for this particular case.</p>\n\n<p>To summarize:</p>\n\n<ul>\n<li>You want to set a \"block template\" for the post type \"page\".</li>\n<li>In this block template you want to have one columns block with 3 column blocks inside with widths of 25%, 50% and 25%</li>\n</ul>\n\n<p>In code this looks like this:</p>\n\n<pre><code>function wpse_354875() {\n $post_type_object = get_post_type_object( 'page' );\n $post_type_object->template = [\n [\n 'core/columns',\n [],\n [\n [\n 'core/column',\n ['width'=>25],\n []\n ],\n [\n 'core/column',\n ['width'=>50],\n []\n ],\n [\n 'core/column',\n ['width'=>25],\n []\n ],\n ]\n ],\n ];\n}\nadd_action( 'init', 'wpse_354875' );\n</code></pre>\n"
},
{
"answer_id": 369722,
"author": "Kyle Bihler",
"author_id": 103355,
"author_profile": "https://wordpress.stackexchange.com/users/103355",
"pm_score": 1,
"selected": false,
"text": "<p>Once you are into the column you can add to the column array other blocks that you can identify. Below is another core/paragraph, but you could easily register your own block that grabs the title in an h1 tag (yourOwnBlocks/h1title in the below). I tried this with other block builder blocks and hooray that works too!! Thanks, Kraftner great tip.</p>\n<pre><code> [ 'core/columns',\n [],\n [\n [\n 'core/column',\n ['width'=>50],\n [\n ['core/paragraph',\n [\n 'placeholder' => __( 'Add Description...', 'wp-rig' ),\n ],\n ],\n ],\n ],\n [\n 'core/column',\n ['width'=>50],\n [\n ['yourOwnBlocks/h1title'],\n ]\n ],\n ],\n ],\n</code></pre>\n"
}
] | 2019/12/18 | [
"https://wordpress.stackexchange.com/questions/354875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179947/"
] | I would like to have 3 editable columns (25, 50, 25) like you can insert in Gutenberg, per default in every new page. How can I do this? If I give the columns to `page.php` they are not editable. | So first of all this is [explained in detail in the documentation](https://developer.wordpress.org/block-editor/developers/block-api/block-templates/), just not exactly for this particular case.
To summarize:
* You want to set a "block template" for the post type "page".
* In this block template you want to have one columns block with 3 column blocks inside with widths of 25%, 50% and 25%
In code this looks like this:
```
function wpse_354875() {
$post_type_object = get_post_type_object( 'page' );
$post_type_object->template = [
[
'core/columns',
[],
[
[
'core/column',
['width'=>25],
[]
],
[
'core/column',
['width'=>50],
[]
],
[
'core/column',
['width'=>25],
[]
],
]
],
];
}
add_action( 'init', 'wpse_354875' );
``` |
354,980 | <p>I'm trying to create a function that sends an email to the admin when a new user registers. I would like the email to contain the users first name, last name, email address, and billing information added via WooCommerce. This is what I have so far, but for some reason $id and $email are the only variables that show up in the email, but nothing else.. What am I doing wrong? lol</p>
<pre><code>function admin_notification($user_id) {
$user = get_userdata( $user_id );
$id = $user->id;
$email = $user->user_email;
$firstname = $user->first_name;
$lastname = $user->last_name;
$phone = get_user_meta($id, 'billing_phone', true);
$address = get_user_meta($id, 'billing_address_1', true);
$city = get_user_meta($id, 'billing_city', true);
$state = get_user_meta($id, 'billing_state', true);
$zip = get_user_meta($id, 'billing_postcode', true);
$headers = array('Content-Type: text/html; charset=UTF-8','From: My WordPress Site <[email protected]>');
$message = '<p>'. $firstname .' '. $lastname .' has requested registration to the website. Please verify their account as soon as possible.</p><hr /><p><strong>First Name:</strong> '.$firstname.'<br><strong>Last Name:</strong> '.$lastname.'<br><strong>Email Address:</strong> '.$email.'<br><strong>Phone Number:</strong> '.$phone.'<br><strong>Address:</strong><br>'.$address.', '.$city.' '.$state.' '.$zip.'</p><br><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td><table border="0" cellspacing="0" cellpadding="0"><tr><td bgcolor="green" style="padding: 12px 18px 12px 18px; -webkit-border-radius:3px; border-radius:3px" align="center"><a href="https://example.com/wp-admin/user-edit.php?user_id='.$id.'" target="_blank" style="font-size: 16px; font-family: Helvetica, Arial, sans-serif; font-weight: normal; color: #ffffff; text-decoration: none; display: inline-block;">Verify User</a></td></tr></table></td></tr></table>';
wp_mail('[email protected]', 'New Customer Registration', $message, $headers);
}
add_action('user_register', 'admin_notification', 10, 1);
</code></pre>
| [
{
"answer_id": 354918,
"author": "Monkey Puzzle",
"author_id": 48568,
"author_profile": "https://wordpress.stackexchange.com/users/48568",
"pm_score": 0,
"selected": false,
"text": "<p>The author of the post (current logged-in user when writing it) will show as the Post Author. However, you can override that by editing the post (edit or quick edit - see screenshot below for quick edit). </p>\n\n<p>Then, you could add a link at the bottom of each article to say something like:</p>\n\n<pre><code>See more posts by CoPeace (link to https://www.copeace.com/author/copeace-drafts or whatever).\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/PvD53.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PvD53.png\" alt=\"quick edit - author change\"></a></p>\n"
},
{
"answer_id": 354924,
"author": "Michael",
"author_id": 4884,
"author_profile": "https://wordpress.stackexchange.com/users/4884",
"pm_score": 1,
"selected": false,
"text": "<p>before making edits, please consider to create a child theme for your customization; <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/advanced-topics/child-themes/</a></p>\n\n<p>to show a link to the author's page (<a href=\"https://developer.wordpress.org/reference/functions/get_author_posts_url/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_author_posts_url/</a>), put this code into the loop of the blog or post template file below the blog post code (please contact the theme's developer for help with where in what file of your theme exactly):</p>\n\n<p><code><a href=\"<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>\" title=\"<?php echo esc_attr( get_the_author() ); ?>\"><?php the_author(); ?></a></code></p>\n\n<p>if not exists, create a template file <strong>author.php</strong> in your (child) theme (<a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#author-display\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/#author-display</a>), possibly starting with a copy of <strong>archive.php</strong> or <strong>index.php</strong> of your theme.</p>\n\n<p>in that file, before the loop, add the code for the author bio:</p>\n\n<p><code><?php the_author_meta( 'description' ); ?></code></p>\n\n<p>for the profile picture you could use the gravatar (<a href=\"https://developer.wordpress.org/reference/functions/get_avatar/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_avatar/</a>)</p>\n"
}
] | 2019/12/20 | [
"https://wordpress.stackexchange.com/questions/354980",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180030/"
] | I'm trying to create a function that sends an email to the admin when a new user registers. I would like the email to contain the users first name, last name, email address, and billing information added via WooCommerce. This is what I have so far, but for some reason $id and $email are the only variables that show up in the email, but nothing else.. What am I doing wrong? lol
```
function admin_notification($user_id) {
$user = get_userdata( $user_id );
$id = $user->id;
$email = $user->user_email;
$firstname = $user->first_name;
$lastname = $user->last_name;
$phone = get_user_meta($id, 'billing_phone', true);
$address = get_user_meta($id, 'billing_address_1', true);
$city = get_user_meta($id, 'billing_city', true);
$state = get_user_meta($id, 'billing_state', true);
$zip = get_user_meta($id, 'billing_postcode', true);
$headers = array('Content-Type: text/html; charset=UTF-8','From: My WordPress Site <[email protected]>');
$message = '<p>'. $firstname .' '. $lastname .' has requested registration to the website. Please verify their account as soon as possible.</p><hr /><p><strong>First Name:</strong> '.$firstname.'<br><strong>Last Name:</strong> '.$lastname.'<br><strong>Email Address:</strong> '.$email.'<br><strong>Phone Number:</strong> '.$phone.'<br><strong>Address:</strong><br>'.$address.', '.$city.' '.$state.' '.$zip.'</p><br><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td><table border="0" cellspacing="0" cellpadding="0"><tr><td bgcolor="green" style="padding: 12px 18px 12px 18px; -webkit-border-radius:3px; border-radius:3px" align="center"><a href="https://example.com/wp-admin/user-edit.php?user_id='.$id.'" target="_blank" style="font-size: 16px; font-family: Helvetica, Arial, sans-serif; font-weight: normal; color: #ffffff; text-decoration: none; display: inline-block;">Verify User</a></td></tr></table></td></tr></table>';
wp_mail('[email protected]', 'New Customer Registration', $message, $headers);
}
add_action('user_register', 'admin_notification', 10, 1);
``` | before making edits, please consider to create a child theme for your customization; <https://developer.wordpress.org/themes/advanced-topics/child-themes/>
to show a link to the author's page (<https://developer.wordpress.org/reference/functions/get_author_posts_url/>), put this code into the loop of the blog or post template file below the blog post code (please contact the theme's developer for help with where in what file of your theme exactly):
`<a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" title="<?php echo esc_attr( get_the_author() ); ?>"><?php the_author(); ?></a>`
if not exists, create a template file **author.php** in your (child) theme (<https://developer.wordpress.org/themes/basics/template-hierarchy/#author-display>), possibly starting with a copy of **archive.php** or **index.php** of your theme.
in that file, before the loop, add the code for the author bio:
`<?php the_author_meta( 'description' ); ?>`
for the profile picture you could use the gravatar (<https://developer.wordpress.org/reference/functions/get_avatar/>) |
355,011 | <p>I'm working on a fill-in-the-blanks plugin (<a href="https://github.com/liquidchurch/lqd-notes" rel="nofollow noreferrer">https://github.com/liquidchurch/lqd-notes</a>) which has been working.</p>
<p>I realized that the plugin was loading its styles, js, and inserting a div on every page, not just its own custom post type ('lqdnotes). So I used a simple if statement to ensure the code is only passed if the cpt is present. </p>
<p>It occurs in the following locations:</p>
<p><strong>lqd-notes.php</strong></p>
<pre class="lang-php prettyprint-override"><code>function lqdnotes_enqueue_css() {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$lqdcssversion = filemtime( LQDNOTES_DIR . 'public/css/lqdnotes.css' );
wp_enqueue_style(
'lqdnotes-css',
plugins_url( 'public/css/lqdnotes.css', __FILE__ ),
array(),
$lqdcssversion
);
}
}
add_action( 'enqueue_block_assets', 'lqdnotes_enqueue_css' );
</code></pre>
<p><strong>public/display-filled.php</strong></p>
<pre class="lang-php prettyprint-override"><code>function lqdnotes_enqueue_display_filled() {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$lqdfilterinputversion = filemtime( LQDNOTES_DIR . 'public/js/lqdnotes-filter-inputs.js' );
wp_enqueue_script(
'lqdnotes-filter-inputs',
LQDNOTES_URL . 'public/js/lqdnotes-filter-inputs.js',
array( 'jquery' ),
$lqdfilterinputversion
);
$ajax_array = array(
'ajax_url' => admin_url( 'admin-ajax.php' )
);
wp_localize_script(
'lqdnotes-filter-inputs',
'lqdnotes_ajax',
$ajax_array );
}
}
add_action( 'wp_enqueue_scripts', 'lqdnotes_enqueue_display_filled' );
</code></pre>
<p><strong>public/modify-display.php</strong></p>
<pre class="lang-php prettyprint-override"><code>function lqdnotes_enqueue_display_blanks() {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$lqdfilterspanversion = filemtime( LQDNOTES_DIR .'public/js/lqdnotes-filter-span.js' );
wp_enqueue_script(
'lqdnotes-filter-spans',
plugin_dir_url( __FILE__ ) . 'js/lqdnotes-filter-span.js',
array(),
$lqdfilterspanversion
);
}
}
add_action( 'wp_enqueue_scripts', 'lqdnotes_enqueue_display_blanks' );
</code></pre>
<pre class="lang-php prettyprint-override"><code>function lqdnotes_add_div( $content ) {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$updated_content = '<div id="message-notes" class="message-notes">' . $content . '</div>';
return $updated_content;
}
}
add_filter( 'the_content', 'lqdnotes_add_div' );
</code></pre>
<p>When I activate the plugin and browser to a page of content (say test.liquidchurch.com) the header and footer display but no page content..and this is occurring on pages that aren't part of the CPT.</p>
<p>If, however, I open one of the CPT pages everything displays correctly (see <a href="https://test.liquidchurch.com/blog/notes/breakthrough/" rel="nofollow noreferrer">https://test.liquidchurch.com/blog/notes/breakthrough/</a>).</p>
<p>To see what a page on test.liquidchurch.com should look like go to liquidchurch.com. As one can see, there is content for the page and if I were to disable the notes plugin on test.liquidchurch.com it would appear there as well (I've disabled the plugin on the live site until this is resolved).</p>
| [
{
"answer_id": 355015,
"author": "davemackey",
"author_id": 43881,
"author_profile": "https://wordpress.stackexchange.com/users/43881",
"pm_score": 0,
"selected": false,
"text": "<p>StackOverflow may be my <a href=\"https://en.wikipedia.org/wiki/Rubber_duck_debugging\" rel=\"nofollow noreferrer\">rubber duck</a>. Almost immediately after publishing the question the solution popped into my mind.</p>\n\n<p>The problem was in the function <code>lqdnotes_add_div</code>. This function took <code>$content</code> (the post content) as a parameter. If post was not of type <code>lqdnotes</code> then it didn't perform any operation on <code>$content</code>...or so I thought.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1218580/what-does-a-php-function-return-by-default\">PHP actually returns null</a> if a return value is not specified, so actually was performing an action on <code>$content</code> - setting it to null.</p>\n\n<p>Add an else clause that explicitly returns the <code>$content</code> I received fixes the issue:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function lqdnotes_add_div( $content ) {\n if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {\n $updated_content = '<div id=\"message-notes\" class=\"message-notes\">' . $content . '</div>';\n return $updated_content;\n } else {\n return $content;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 355027,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>I realize you've already answered your issue. However, I think there is some additional explanation possible to give more clarity to the issue and the solution.</p>\n\n<p>The issue is your <code>lqdnotes_add_div()</code> function. This is hooked to a filter - <code>the_content</code>.</p>\n\n<p>In WordPress, any time you use a filter, your filter function must return a value for the item being filtered. This might be a string, array, or boolean. In this case, <code>$content</code> is a string, and a string must be returned.</p>\n\n<p>Your filter function only returned a value if the post type was \"lqdnotes\". In all other cases a null value was returned.</p>\n\n<p>While you do need to return a value for <code>$content</code>, you do not need to do this with an <code>else</code> condition. In fact, it is a good standard practice to make sure there is at least a return value at the end of any filter function to provide for returning an unfiltered result if any of the function's other conditions are not met.</p>\n\n<pre><code>function lqdnotes_add_div( $content ) {\n if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {\n $updated_content = '<div id=\"message-notes\" class=\"message-notes\">' . $content . '</div>';\n return $updated_content;\n }\n return $content;\n}\nadd_filter( 'the_content', 'lqdnotes_add_div' );\n</code></pre>\n"
}
] | 2019/12/20 | [
"https://wordpress.stackexchange.com/questions/355011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43881/"
] | I'm working on a fill-in-the-blanks plugin (<https://github.com/liquidchurch/lqd-notes>) which has been working.
I realized that the plugin was loading its styles, js, and inserting a div on every page, not just its own custom post type ('lqdnotes). So I used a simple if statement to ensure the code is only passed if the cpt is present.
It occurs in the following locations:
**lqd-notes.php**
```php
function lqdnotes_enqueue_css() {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$lqdcssversion = filemtime( LQDNOTES_DIR . 'public/css/lqdnotes.css' );
wp_enqueue_style(
'lqdnotes-css',
plugins_url( 'public/css/lqdnotes.css', __FILE__ ),
array(),
$lqdcssversion
);
}
}
add_action( 'enqueue_block_assets', 'lqdnotes_enqueue_css' );
```
**public/display-filled.php**
```php
function lqdnotes_enqueue_display_filled() {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$lqdfilterinputversion = filemtime( LQDNOTES_DIR . 'public/js/lqdnotes-filter-inputs.js' );
wp_enqueue_script(
'lqdnotes-filter-inputs',
LQDNOTES_URL . 'public/js/lqdnotes-filter-inputs.js',
array( 'jquery' ),
$lqdfilterinputversion
);
$ajax_array = array(
'ajax_url' => admin_url( 'admin-ajax.php' )
);
wp_localize_script(
'lqdnotes-filter-inputs',
'lqdnotes_ajax',
$ajax_array );
}
}
add_action( 'wp_enqueue_scripts', 'lqdnotes_enqueue_display_filled' );
```
**public/modify-display.php**
```php
function lqdnotes_enqueue_display_blanks() {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$lqdfilterspanversion = filemtime( LQDNOTES_DIR .'public/js/lqdnotes-filter-span.js' );
wp_enqueue_script(
'lqdnotes-filter-spans',
plugin_dir_url( __FILE__ ) . 'js/lqdnotes-filter-span.js',
array(),
$lqdfilterspanversion
);
}
}
add_action( 'wp_enqueue_scripts', 'lqdnotes_enqueue_display_blanks' );
```
```php
function lqdnotes_add_div( $content ) {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$updated_content = '<div id="message-notes" class="message-notes">' . $content . '</div>';
return $updated_content;
}
}
add_filter( 'the_content', 'lqdnotes_add_div' );
```
When I activate the plugin and browser to a page of content (say test.liquidchurch.com) the header and footer display but no page content..and this is occurring on pages that aren't part of the CPT.
If, however, I open one of the CPT pages everything displays correctly (see <https://test.liquidchurch.com/blog/notes/breakthrough/>).
To see what a page on test.liquidchurch.com should look like go to liquidchurch.com. As one can see, there is content for the page and if I were to disable the notes plugin on test.liquidchurch.com it would appear there as well (I've disabled the plugin on the live site until this is resolved). | I realize you've already answered your issue. However, I think there is some additional explanation possible to give more clarity to the issue and the solution.
The issue is your `lqdnotes_add_div()` function. This is hooked to a filter - `the_content`.
In WordPress, any time you use a filter, your filter function must return a value for the item being filtered. This might be a string, array, or boolean. In this case, `$content` is a string, and a string must be returned.
Your filter function only returned a value if the post type was "lqdnotes". In all other cases a null value was returned.
While you do need to return a value for `$content`, you do not need to do this with an `else` condition. In fact, it is a good standard practice to make sure there is at least a return value at the end of any filter function to provide for returning an unfiltered result if any of the function's other conditions are not met.
```
function lqdnotes_add_div( $content ) {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$updated_content = '<div id="message-notes" class="message-notes">' . $content . '</div>';
return $updated_content;
}
return $content;
}
add_filter( 'the_content', 'lqdnotes_add_div' );
``` |
355,052 | <p>Was called incorrectly. The seventh parameter passed to an <code>add_submenu_page()</code> should be an integer representing menu position. Please see Debugging in WordPress for more information. (This message was added in version 5.3.0.) in <code>/home3/prombooking/listandlink.com/wp-includes/functions.php</code> on line 4986</p>
| [
{
"answer_id": 355015,
"author": "davemackey",
"author_id": 43881,
"author_profile": "https://wordpress.stackexchange.com/users/43881",
"pm_score": 0,
"selected": false,
"text": "<p>StackOverflow may be my <a href=\"https://en.wikipedia.org/wiki/Rubber_duck_debugging\" rel=\"nofollow noreferrer\">rubber duck</a>. Almost immediately after publishing the question the solution popped into my mind.</p>\n\n<p>The problem was in the function <code>lqdnotes_add_div</code>. This function took <code>$content</code> (the post content) as a parameter. If post was not of type <code>lqdnotes</code> then it didn't perform any operation on <code>$content</code>...or so I thought.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1218580/what-does-a-php-function-return-by-default\">PHP actually returns null</a> if a return value is not specified, so actually was performing an action on <code>$content</code> - setting it to null.</p>\n\n<p>Add an else clause that explicitly returns the <code>$content</code> I received fixes the issue:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function lqdnotes_add_div( $content ) {\n if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {\n $updated_content = '<div id=\"message-notes\" class=\"message-notes\">' . $content . '</div>';\n return $updated_content;\n } else {\n return $content;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 355027,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>I realize you've already answered your issue. However, I think there is some additional explanation possible to give more clarity to the issue and the solution.</p>\n\n<p>The issue is your <code>lqdnotes_add_div()</code> function. This is hooked to a filter - <code>the_content</code>.</p>\n\n<p>In WordPress, any time you use a filter, your filter function must return a value for the item being filtered. This might be a string, array, or boolean. In this case, <code>$content</code> is a string, and a string must be returned.</p>\n\n<p>Your filter function only returned a value if the post type was \"lqdnotes\". In all other cases a null value was returned.</p>\n\n<p>While you do need to return a value for <code>$content</code>, you do not need to do this with an <code>else</code> condition. In fact, it is a good standard practice to make sure there is at least a return value at the end of any filter function to provide for returning an unfiltered result if any of the function's other conditions are not met.</p>\n\n<pre><code>function lqdnotes_add_div( $content ) {\n if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {\n $updated_content = '<div id=\"message-notes\" class=\"message-notes\">' . $content . '</div>';\n return $updated_content;\n }\n return $content;\n}\nadd_filter( 'the_content', 'lqdnotes_add_div' );\n</code></pre>\n"
}
] | 2019/12/21 | [
"https://wordpress.stackexchange.com/questions/355052",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180092/"
] | Was called incorrectly. The seventh parameter passed to an `add_submenu_page()` should be an integer representing menu position. Please see Debugging in WordPress for more information. (This message was added in version 5.3.0.) in `/home3/prombooking/listandlink.com/wp-includes/functions.php` on line 4986 | I realize you've already answered your issue. However, I think there is some additional explanation possible to give more clarity to the issue and the solution.
The issue is your `lqdnotes_add_div()` function. This is hooked to a filter - `the_content`.
In WordPress, any time you use a filter, your filter function must return a value for the item being filtered. This might be a string, array, or boolean. In this case, `$content` is a string, and a string must be returned.
Your filter function only returned a value if the post type was "lqdnotes". In all other cases a null value was returned.
While you do need to return a value for `$content`, you do not need to do this with an `else` condition. In fact, it is a good standard practice to make sure there is at least a return value at the end of any filter function to provide for returning an unfiltered result if any of the function's other conditions are not met.
```
function lqdnotes_add_div( $content ) {
if ( get_post_type( get_the_ID() ) == 'lqdnotes' ) {
$updated_content = '<div id="message-notes" class="message-notes">' . $content . '</div>';
return $updated_content;
}
return $content;
}
add_filter( 'the_content', 'lqdnotes_add_div' );
``` |
355,114 | <p>I am working on a plugin that registers custom new endpoints in every update and we need to Flush Rewrite Rules after every update of the plugin.</p>
<p>Flushing Rewrite Rules are easy after activation of the plugin and there is a lot of tutorials out there about this</p>
<p>But in the case of Flushing Rewrite Rules after Update
I can't find any solution</p>
| [
{
"answer_id": 355132,
"author": "Will",
"author_id": 48698,
"author_profile": "https://wordpress.stackexchange.com/users/48698",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't verified this but you could try the <a href=\"https://developer.wordpress.org/reference/hooks/upgrader_process_complete/\" rel=\"nofollow noreferrer\">upgrader_process_complete</a> hook.\n<a href=\"https://pluginrepublic.com/wordpress-plugin-update-hook-upgrader_process_complete/\" rel=\"nofollow noreferrer\">More information on that hook.</a> </p>\n\n<p>like follows </p>\n\n<pre><code>function wp_answ_355114() {\n\nflush_rewrite_rules(); \n\n}\n\ndo_action( 'upgrader_process_complete', 'wp_answ_355114' );\n</code></pre>\n"
},
{
"answer_id": 377921,
"author": "kiwiot",
"author_id": 71357,
"author_profile": "https://wordpress.stackexchange.com/users/71357",
"pm_score": 2,
"selected": false,
"text": "<p>Your answer above was close but is should be</p>\n<pre><code>add_action( 'upgrader_process_complete', 'wp_answ_355114' );\n</code></pre>\n<p>not</p>\n<pre><code>do_action( 'upgrader_process_complete', 'wp_answ_355114' );\n</code></pre>\n<p>noting that this is only the case when a plugin is updated view WP plugin updates.</p>\n"
}
] | 2019/12/23 | [
"https://wordpress.stackexchange.com/questions/355114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86669/"
] | I am working on a plugin that registers custom new endpoints in every update and we need to Flush Rewrite Rules after every update of the plugin.
Flushing Rewrite Rules are easy after activation of the plugin and there is a lot of tutorials out there about this
But in the case of Flushing Rewrite Rules after Update
I can't find any solution | Your answer above was close but is should be
```
add_action( 'upgrader_process_complete', 'wp_answ_355114' );
```
not
```
do_action( 'upgrader_process_complete', 'wp_answ_355114' );
```
noting that this is only the case when a plugin is updated view WP plugin updates. |
355,147 | <p>I have a website that uses a plugin that lets me add categories and tags to pages. </p>
<p>Is there a way of automatically changing the color of a menu item linked to all pages with a particular tag or category?</p>
<p>Specifically, I want to add the class "unwatched" to the menu item of any page that has been tagged with the "unwatched" tag.</p>
<p>I have tried the following code but I'm sure I've got it wrong: (it didn't work)</p>
<pre><code>add_filter('nav_menu_css_class', 'custom_nav_menu_css_class', 10, 2 );
function custom_nav_menu_css_class( $classes, $item ) {
if( 'tag' === $item->object ){
array_push( $classes, 'unwatched' );
}
return $classes;
}
</code></pre>
| [
{
"answer_id": 355194,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using <code>array_push()</code> try using <code>$item->classes[] = 'unwatched';</code></p>\n\n<p>Although the more I look at it, where is your code checking if the tag is 'unwatched'?</p>\n\n<p>You're pushing 'unwatched' into the classes array but your tag check isn't referencing it?</p>\n\n<p>Is there more code that's not displayed here?</p>\n\n<p><strong>UPDATE</strong>\nLooking at your second effort I think I understand where the issue is... ...when a page is loaded you're checking to see if the tag is present for the page that is loaded by using 'get_the_tags()', you're not checking if all of the pages associated with the menu items have that tag. Since the result returns TRUE for that page, then the <em>foreach</em> adds the class to each.</p>\n\n<p>What you need to do is, in the <em>foreach</em>, check the tags for each specific page/post ID and then add the class dependent on that. So within the <em>foreach</em> you'd need <code>get_the_tags( $item->ID )</code>. May need more work than just that to ensure you're getting the ID of each item, but I think that's the right way to go about doing applying the class.</p>\n"
},
{
"answer_id": 355271,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 0,
"selected": false,
"text": "<p>My next effort:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_tags = get_the_tags();\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>This has an interesting effect - if the page I'm looking at has the 'unwatched' tag, ALL my menu items have the 'unwatched' class; conversely, if the page I'm looking at doesn't have the 'unwatched' tag, NONE of my menu items have the 'unwatched' class.</p>\n\n<p>Maybe it's not possible to achieve this, but what I want is for the 'unwatched' class to be on every menu item linked to a page that has the 'unwatched' tag, and none of the others, regardless of which page I'm currently looking at.</p>\n"
},
{
"answer_id": 356024,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 2,
"selected": true,
"text": "<p>OK, got it :-)</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );\n $post_tags = get_the_tags( $post_id );\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is</p>\n\n<pre><code>li.unwatched > a {\n color: FORESTGREEN;\n}\n</code></pre>\n"
}
] | 2019/12/24 | [
"https://wordpress.stackexchange.com/questions/355147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119832/"
] | I have a website that uses a plugin that lets me add categories and tags to pages.
Is there a way of automatically changing the color of a menu item linked to all pages with a particular tag or category?
Specifically, I want to add the class "unwatched" to the menu item of any page that has been tagged with the "unwatched" tag.
I have tried the following code but I'm sure I've got it wrong: (it didn't work)
```
add_filter('nav_menu_css_class', 'custom_nav_menu_css_class', 10, 2 );
function custom_nav_menu_css_class( $classes, $item ) {
if( 'tag' === $item->object ){
array_push( $classes, 'unwatched' );
}
return $classes;
}
``` | OK, got it :-)
```
add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );
function add_nav_menu_item_class( $items ) {
foreach ( $items as $item ) {
$post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$post_tags = get_the_tags( $post_id );
if ( $post_tags ) {
foreach( $post_tags as $tag ) {
if ( $tag->name == 'unwatched' ) {
$item->classes[] = 'unwatched';
}
}
}
}
return $items;
}
```
The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is
```
li.unwatched > a {
color: FORESTGREEN;
}
``` |
355,153 | <p>I am not getting the Wordpress Admin login page. It is displaying Error 404 Not found.
Can anyone help me exactly what could be the issue?</p>
<p><a href="https://i.stack.imgur.com/OFGvo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OFGvo.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 355194,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using <code>array_push()</code> try using <code>$item->classes[] = 'unwatched';</code></p>\n\n<p>Although the more I look at it, where is your code checking if the tag is 'unwatched'?</p>\n\n<p>You're pushing 'unwatched' into the classes array but your tag check isn't referencing it?</p>\n\n<p>Is there more code that's not displayed here?</p>\n\n<p><strong>UPDATE</strong>\nLooking at your second effort I think I understand where the issue is... ...when a page is loaded you're checking to see if the tag is present for the page that is loaded by using 'get_the_tags()', you're not checking if all of the pages associated with the menu items have that tag. Since the result returns TRUE for that page, then the <em>foreach</em> adds the class to each.</p>\n\n<p>What you need to do is, in the <em>foreach</em>, check the tags for each specific page/post ID and then add the class dependent on that. So within the <em>foreach</em> you'd need <code>get_the_tags( $item->ID )</code>. May need more work than just that to ensure you're getting the ID of each item, but I think that's the right way to go about doing applying the class.</p>\n"
},
{
"answer_id": 355271,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 0,
"selected": false,
"text": "<p>My next effort:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_tags = get_the_tags();\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>This has an interesting effect - if the page I'm looking at has the 'unwatched' tag, ALL my menu items have the 'unwatched' class; conversely, if the page I'm looking at doesn't have the 'unwatched' tag, NONE of my menu items have the 'unwatched' class.</p>\n\n<p>Maybe it's not possible to achieve this, but what I want is for the 'unwatched' class to be on every menu item linked to a page that has the 'unwatched' tag, and none of the others, regardless of which page I'm currently looking at.</p>\n"
},
{
"answer_id": 356024,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 2,
"selected": true,
"text": "<p>OK, got it :-)</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );\n $post_tags = get_the_tags( $post_id );\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is</p>\n\n<pre><code>li.unwatched > a {\n color: FORESTGREEN;\n}\n</code></pre>\n"
}
] | 2019/12/24 | [
"https://wordpress.stackexchange.com/questions/355153",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180177/"
] | I am not getting the Wordpress Admin login page. It is displaying Error 404 Not found.
Can anyone help me exactly what could be the issue?
[](https://i.stack.imgur.com/OFGvo.png) | OK, got it :-)
```
add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );
function add_nav_menu_item_class( $items ) {
foreach ( $items as $item ) {
$post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$post_tags = get_the_tags( $post_id );
if ( $post_tags ) {
foreach( $post_tags as $tag ) {
if ( $tag->name == 'unwatched' ) {
$item->classes[] = 'unwatched';
}
}
}
}
return $items;
}
```
The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is
```
li.unwatched > a {
color: FORESTGREEN;
}
``` |
355,164 | <p>I activated wordpress theme <code>twenty twenty</code> and make some changes in it like background color , change default contents and landing pages etc . </p>
<p>Can I export this modified theme and import in another wordpress website so that I dont have to make same changes again and again ?</p>
<p>We have to replicate same content around 40 wordpress websites which we are trying to do it via multisite but problem with multisite is it install default content of a theme and not a modified one.
Can anyone advise me how to achieve this ?</p>
| [
{
"answer_id": 355194,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using <code>array_push()</code> try using <code>$item->classes[] = 'unwatched';</code></p>\n\n<p>Although the more I look at it, where is your code checking if the tag is 'unwatched'?</p>\n\n<p>You're pushing 'unwatched' into the classes array but your tag check isn't referencing it?</p>\n\n<p>Is there more code that's not displayed here?</p>\n\n<p><strong>UPDATE</strong>\nLooking at your second effort I think I understand where the issue is... ...when a page is loaded you're checking to see if the tag is present for the page that is loaded by using 'get_the_tags()', you're not checking if all of the pages associated with the menu items have that tag. Since the result returns TRUE for that page, then the <em>foreach</em> adds the class to each.</p>\n\n<p>What you need to do is, in the <em>foreach</em>, check the tags for each specific page/post ID and then add the class dependent on that. So within the <em>foreach</em> you'd need <code>get_the_tags( $item->ID )</code>. May need more work than just that to ensure you're getting the ID of each item, but I think that's the right way to go about doing applying the class.</p>\n"
},
{
"answer_id": 355271,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 0,
"selected": false,
"text": "<p>My next effort:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_tags = get_the_tags();\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>This has an interesting effect - if the page I'm looking at has the 'unwatched' tag, ALL my menu items have the 'unwatched' class; conversely, if the page I'm looking at doesn't have the 'unwatched' tag, NONE of my menu items have the 'unwatched' class.</p>\n\n<p>Maybe it's not possible to achieve this, but what I want is for the 'unwatched' class to be on every menu item linked to a page that has the 'unwatched' tag, and none of the others, regardless of which page I'm currently looking at.</p>\n"
},
{
"answer_id": 356024,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 2,
"selected": true,
"text": "<p>OK, got it :-)</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );\n $post_tags = get_the_tags( $post_id );\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is</p>\n\n<pre><code>li.unwatched > a {\n color: FORESTGREEN;\n}\n</code></pre>\n"
}
] | 2019/12/24 | [
"https://wordpress.stackexchange.com/questions/355164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180185/"
] | I activated wordpress theme `twenty twenty` and make some changes in it like background color , change default contents and landing pages etc .
Can I export this modified theme and import in another wordpress website so that I dont have to make same changes again and again ?
We have to replicate same content around 40 wordpress websites which we are trying to do it via multisite but problem with multisite is it install default content of a theme and not a modified one.
Can anyone advise me how to achieve this ? | OK, got it :-)
```
add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );
function add_nav_menu_item_class( $items ) {
foreach ( $items as $item ) {
$post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$post_tags = get_the_tags( $post_id );
if ( $post_tags ) {
foreach( $post_tags as $tag ) {
if ( $tag->name == 'unwatched' ) {
$item->classes[] = 'unwatched';
}
}
}
}
return $items;
}
```
The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is
```
li.unwatched > a {
color: FORESTGREEN;
}
``` |
355,174 | <p>Not sure what I changed in my Wordpress some days ago but today I was not able to update/install any plugin. I followed <a href="https://community.bitnami.com/t/wordpress-permissions-unable-to-create-directory/42048/3" rel="nofollow noreferrer">https://community.bitnami.com/t/wordpress-permissions-unable-to-create-directory/42048/3</a> and applied the following permissions:</p>
<pre><code>sudo find ~/apps/wordpress/htdocs/ -type f -exec chmod 644 {} \;
sudo find ~/apps/wordpress/htdocs/ -type d -exec chmod 755 {} \;
sudo chmod 750 ~/apps/wordpress/htdocs/wp-config.php
sudo find ~/apps/wordpress/htdocs/wp-content -type d -exec chmod 775 {} \;
sudo find ~/apps/wordpress/htdocs/wp-content -type f -exec chmod 664 {} \;
sudo chmod 750 ~/apps/wordpress/htdocs
sudo chown -R bitnami:daemon ~/apps/wordpress/htdocs
sudo chown -R bitnami:daemon ~/apps/wordpress/htdocs/wp-content/plugins
sudo chown -R bitnami:bitnami ~/apps/wordpress/htdocs/wp-content/upgrade
sudo chown -R daemon:daemon ~/apps/wordpress/htdocs/wp-content/uploads
</code></pre>
<p>Now I CAN update and install plugins but:<br>
- It takes longer, roughly twice as much time than some days ago (before it broke).<br>
- It tells me the install/update was unsuccesful even though it did it!</p>
<blockquote>
<p>The update cannot be installed because we were unable to copy some files. This is usually due to inconsistent file permissions.</p>
</blockquote>
<p>Of course, it is not that bad, but I would like to have it as it should be, not with such a result.<br>
Any idea?</p>
| [
{
"answer_id": 355194,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using <code>array_push()</code> try using <code>$item->classes[] = 'unwatched';</code></p>\n\n<p>Although the more I look at it, where is your code checking if the tag is 'unwatched'?</p>\n\n<p>You're pushing 'unwatched' into the classes array but your tag check isn't referencing it?</p>\n\n<p>Is there more code that's not displayed here?</p>\n\n<p><strong>UPDATE</strong>\nLooking at your second effort I think I understand where the issue is... ...when a page is loaded you're checking to see if the tag is present for the page that is loaded by using 'get_the_tags()', you're not checking if all of the pages associated with the menu items have that tag. Since the result returns TRUE for that page, then the <em>foreach</em> adds the class to each.</p>\n\n<p>What you need to do is, in the <em>foreach</em>, check the tags for each specific page/post ID and then add the class dependent on that. So within the <em>foreach</em> you'd need <code>get_the_tags( $item->ID )</code>. May need more work than just that to ensure you're getting the ID of each item, but I think that's the right way to go about doing applying the class.</p>\n"
},
{
"answer_id": 355271,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 0,
"selected": false,
"text": "<p>My next effort:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_tags = get_the_tags();\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>This has an interesting effect - if the page I'm looking at has the 'unwatched' tag, ALL my menu items have the 'unwatched' class; conversely, if the page I'm looking at doesn't have the 'unwatched' tag, NONE of my menu items have the 'unwatched' class.</p>\n\n<p>Maybe it's not possible to achieve this, but what I want is for the 'unwatched' class to be on every menu item linked to a page that has the 'unwatched' tag, and none of the others, regardless of which page I'm currently looking at.</p>\n"
},
{
"answer_id": 356024,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 2,
"selected": true,
"text": "<p>OK, got it :-)</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );\n $post_tags = get_the_tags( $post_id );\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is</p>\n\n<pre><code>li.unwatched > a {\n color: FORESTGREEN;\n}\n</code></pre>\n"
}
] | 2019/12/24 | [
"https://wordpress.stackexchange.com/questions/355174",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179485/"
] | Not sure what I changed in my Wordpress some days ago but today I was not able to update/install any plugin. I followed <https://community.bitnami.com/t/wordpress-permissions-unable-to-create-directory/42048/3> and applied the following permissions:
```
sudo find ~/apps/wordpress/htdocs/ -type f -exec chmod 644 {} \;
sudo find ~/apps/wordpress/htdocs/ -type d -exec chmod 755 {} \;
sudo chmod 750 ~/apps/wordpress/htdocs/wp-config.php
sudo find ~/apps/wordpress/htdocs/wp-content -type d -exec chmod 775 {} \;
sudo find ~/apps/wordpress/htdocs/wp-content -type f -exec chmod 664 {} \;
sudo chmod 750 ~/apps/wordpress/htdocs
sudo chown -R bitnami:daemon ~/apps/wordpress/htdocs
sudo chown -R bitnami:daemon ~/apps/wordpress/htdocs/wp-content/plugins
sudo chown -R bitnami:bitnami ~/apps/wordpress/htdocs/wp-content/upgrade
sudo chown -R daemon:daemon ~/apps/wordpress/htdocs/wp-content/uploads
```
Now I CAN update and install plugins but:
- It takes longer, roughly twice as much time than some days ago (before it broke).
- It tells me the install/update was unsuccesful even though it did it!
>
> The update cannot be installed because we were unable to copy some files. This is usually due to inconsistent file permissions.
>
>
>
Of course, it is not that bad, but I would like to have it as it should be, not with such a result.
Any idea? | OK, got it :-)
```
add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );
function add_nav_menu_item_class( $items ) {
foreach ( $items as $item ) {
$post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$post_tags = get_the_tags( $post_id );
if ( $post_tags ) {
foreach( $post_tags as $tag ) {
if ( $tag->name == 'unwatched' ) {
$item->classes[] = 'unwatched';
}
}
}
}
return $items;
}
```
The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is
```
li.unwatched > a {
color: FORESTGREEN;
}
``` |
355,180 | <p>Cannot modify header information - headers already sent by (output started at /wp-includes/class-wp-post-type.php:613) in /wp-includes/functions.php on line 6029</p>
<p>This error has seemed to follow me around since WP 5.3 where 'supports' needs to be an array. I've been able to successfully clear out the error for a small handful of sites by changing the order of the CPT args (throwing 'supports' at the end), but on others, the error still persists. I've always used an array for 'supports', but for some reason, this error is still persisting... Maybe it's something else in the CPT? I know it's the CPT for sure because removing the CPT code resolves the error. Can anyone tell me what I'm missing?</p>
<pre><code>function rich_review() {
$labels = array(
'name' => _x( 'Reviews', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Review', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Reviews', 'text_domain' ),
'name_admin_bar' => __( 'Reviews', 'text_domain' ),
'archives' => __( 'Review Archives', 'text_domain' ),
'attributes' => __( 'Review Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Review', 'text_domain' ),
'description' => __( 'Rich reviews', 'text_domain' ),
'labels' => $labels,
'taxonomies' => 'rich_review_tax',
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'supports' => array('title', 'editor'),
);
register_post_type( 'reviews', $args );
}
add_action( 'init', 'rich_review', 0 );
</code></pre>
| [
{
"answer_id": 355194,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using <code>array_push()</code> try using <code>$item->classes[] = 'unwatched';</code></p>\n\n<p>Although the more I look at it, where is your code checking if the tag is 'unwatched'?</p>\n\n<p>You're pushing 'unwatched' into the classes array but your tag check isn't referencing it?</p>\n\n<p>Is there more code that's not displayed here?</p>\n\n<p><strong>UPDATE</strong>\nLooking at your second effort I think I understand where the issue is... ...when a page is loaded you're checking to see if the tag is present for the page that is loaded by using 'get_the_tags()', you're not checking if all of the pages associated with the menu items have that tag. Since the result returns TRUE for that page, then the <em>foreach</em> adds the class to each.</p>\n\n<p>What you need to do is, in the <em>foreach</em>, check the tags for each specific page/post ID and then add the class dependent on that. So within the <em>foreach</em> you'd need <code>get_the_tags( $item->ID )</code>. May need more work than just that to ensure you're getting the ID of each item, but I think that's the right way to go about doing applying the class.</p>\n"
},
{
"answer_id": 355271,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 0,
"selected": false,
"text": "<p>My next effort:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_tags = get_the_tags();\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>This has an interesting effect - if the page I'm looking at has the 'unwatched' tag, ALL my menu items have the 'unwatched' class; conversely, if the page I'm looking at doesn't have the 'unwatched' tag, NONE of my menu items have the 'unwatched' class.</p>\n\n<p>Maybe it's not possible to achieve this, but what I want is for the 'unwatched' class to be on every menu item linked to a page that has the 'unwatched' tag, and none of the others, regardless of which page I'm currently looking at.</p>\n"
},
{
"answer_id": 356024,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 2,
"selected": true,
"text": "<p>OK, got it :-)</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );\n $post_tags = get_the_tags( $post_id );\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is</p>\n\n<pre><code>li.unwatched > a {\n color: FORESTGREEN;\n}\n</code></pre>\n"
}
] | 2019/12/24 | [
"https://wordpress.stackexchange.com/questions/355180",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145742/"
] | Cannot modify header information - headers already sent by (output started at /wp-includes/class-wp-post-type.php:613) in /wp-includes/functions.php on line 6029
This error has seemed to follow me around since WP 5.3 where 'supports' needs to be an array. I've been able to successfully clear out the error for a small handful of sites by changing the order of the CPT args (throwing 'supports' at the end), but on others, the error still persists. I've always used an array for 'supports', but for some reason, this error is still persisting... Maybe it's something else in the CPT? I know it's the CPT for sure because removing the CPT code resolves the error. Can anyone tell me what I'm missing?
```
function rich_review() {
$labels = array(
'name' => _x( 'Reviews', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Review', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Reviews', 'text_domain' ),
'name_admin_bar' => __( 'Reviews', 'text_domain' ),
'archives' => __( 'Review Archives', 'text_domain' ),
'attributes' => __( 'Review Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'view_items' => __( 'View Items', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into item', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter items list', 'text_domain' ),
);
$args = array(
'label' => __( 'Review', 'text_domain' ),
'description' => __( 'Rich reviews', 'text_domain' ),
'labels' => $labels,
'taxonomies' => 'rich_review_tax',
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'supports' => array('title', 'editor'),
);
register_post_type( 'reviews', $args );
}
add_action( 'init', 'rich_review', 0 );
``` | OK, got it :-)
```
add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );
function add_nav_menu_item_class( $items ) {
foreach ( $items as $item ) {
$post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$post_tags = get_the_tags( $post_id );
if ( $post_tags ) {
foreach( $post_tags as $tag ) {
if ( $tag->name == 'unwatched' ) {
$item->classes[] = 'unwatched';
}
}
}
}
return $items;
}
```
The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is
```
li.unwatched > a {
color: FORESTGREEN;
}
``` |
355,198 | <p>I am using Jevelin theme and their Lightbox should showing image caption from alt attribute. Hovewer it doesn't works. </p>
<p>Here is the link: <a href="https://www.coleopterafarm.cz/galerie-zlatohlavci/" rel="nofollow noreferrer">https://www.coleopterafarm.cz/galerie-zlatohlavci/</a></p>
<p>I am wondering around forums and tips but still without a success.</p>
<p>Could anyone help me with this please? Thank you! :)</p>
| [
{
"answer_id": 355194,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using <code>array_push()</code> try using <code>$item->classes[] = 'unwatched';</code></p>\n\n<p>Although the more I look at it, where is your code checking if the tag is 'unwatched'?</p>\n\n<p>You're pushing 'unwatched' into the classes array but your tag check isn't referencing it?</p>\n\n<p>Is there more code that's not displayed here?</p>\n\n<p><strong>UPDATE</strong>\nLooking at your second effort I think I understand where the issue is... ...when a page is loaded you're checking to see if the tag is present for the page that is loaded by using 'get_the_tags()', you're not checking if all of the pages associated with the menu items have that tag. Since the result returns TRUE for that page, then the <em>foreach</em> adds the class to each.</p>\n\n<p>What you need to do is, in the <em>foreach</em>, check the tags for each specific page/post ID and then add the class dependent on that. So within the <em>foreach</em> you'd need <code>get_the_tags( $item->ID )</code>. May need more work than just that to ensure you're getting the ID of each item, but I think that's the right way to go about doing applying the class.</p>\n"
},
{
"answer_id": 355271,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 0,
"selected": false,
"text": "<p>My next effort:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_tags = get_the_tags();\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>This has an interesting effect - if the page I'm looking at has the 'unwatched' tag, ALL my menu items have the 'unwatched' class; conversely, if the page I'm looking at doesn't have the 'unwatched' tag, NONE of my menu items have the 'unwatched' class.</p>\n\n<p>Maybe it's not possible to achieve this, but what I want is for the 'unwatched' class to be on every menu item linked to a page that has the 'unwatched' tag, and none of the others, regardless of which page I'm currently looking at.</p>\n"
},
{
"answer_id": 356024,
"author": "cobberas63",
"author_id": 119832,
"author_profile": "https://wordpress.stackexchange.com/users/119832",
"pm_score": 2,
"selected": true,
"text": "<p>OK, got it :-)</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );\n\nfunction add_nav_menu_item_class( $items ) {\n foreach ( $items as $item ) {\n $post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );\n $post_tags = get_the_tags( $post_id );\n if ( $post_tags ) {\n foreach( $post_tags as $tag ) {\n if ( $tag->name == 'unwatched' ) {\n $item->classes[] = 'unwatched';\n }\n }\n }\n }\n return $items;\n}\n</code></pre>\n\n<p>The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is</p>\n\n<pre><code>li.unwatched > a {\n color: FORESTGREEN;\n}\n</code></pre>\n"
}
] | 2019/12/24 | [
"https://wordpress.stackexchange.com/questions/355198",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180202/"
] | I am using Jevelin theme and their Lightbox should showing image caption from alt attribute. Hovewer it doesn't works.
Here is the link: <https://www.coleopterafarm.cz/galerie-zlatohlavci/>
I am wondering around forums and tips but still without a success.
Could anyone help me with this please? Thank you! :) | OK, got it :-)
```
add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' );
function add_nav_menu_item_class( $items ) {
foreach ( $items as $item ) {
$post_id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$post_tags = get_the_tags( $post_id );
if ( $post_tags ) {
foreach( $post_tags as $tag ) {
if ( $tag->name == 'unwatched' ) {
$item->classes[] = 'unwatched';
}
}
}
}
return $items;
}
```
The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is
```
li.unwatched > a {
color: FORESTGREEN;
}
``` |
355,228 | <p>Any idea on how I can totally disable or entirely remove the default/Native Wordpress video player?</p>
| [
{
"answer_id": 355229,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 4,
"selected": true,
"text": "<p>welcome aboard. </p>\n\n<p>WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to <strong>your theme's</strong> <code>functions.php</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('wp-mediaelement');\n wp_deregister_style('wp-mediaelement');\n}\nadd_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n\n<p>PS. This code de-register mediaelements.js from all WordPress (with your current theme).</p>\n"
},
{
"answer_id": 409362,
"author": "Mahdi",
"author_id": 225629,
"author_profile": "https://wordpress.stackexchange.com/users/225629",
"pm_score": 0,
"selected": false,
"text": "<p>I just tested this method, by using this piece of code you will eliminate watching online option from users. The file will be automatically downloaded as somebody enters the page.</p>\n"
},
{
"answer_id": 413231,
"author": "MarkJ",
"author_id": 165181,
"author_profile": "https://wordpress.stackexchange.com/users/165181",
"pm_score": 0,
"selected": false,
"text": "<p>Serkan's answer removed only some mediaelement files for me.\nThis removed it completely:</p>\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('mediaelement');\n wp_deregister_style('mediaelement');\n }\n add_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n"
}
] | 2019/12/25 | [
"https://wordpress.stackexchange.com/questions/355228",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180230/"
] | Any idea on how I can totally disable or entirely remove the default/Native Wordpress video player? | welcome aboard.
WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to **your theme's** `functions.php`
```php
function deregister_media_elements(){
wp_deregister_script('wp-mediaelement');
wp_deregister_style('wp-mediaelement');
}
add_action('wp_enqueue_scripts','deregister_media_elements');
```
PS. This code de-register mediaelements.js from all WordPress (with your current theme). |
355,267 | <p>Is this because of Wordpress, PHP, or the Theme? (or some combination)</p>
<p>A client of mine has a Wordpress site that's been working just fine for years, but recently started getting the following errors pulling up in it's sidebars:</p>
<p>Warning: Invalid argument supplied for foreach() in /wp-content/themes/epsilon/page-threecolumn.php on line 29</p>
<p>Been thinking it may have to do with upgrades to both Wordpress and PHP. Theme is no longer supported. Here is what the code looks like in that area:</p>
<pre><code> <div class="col-234">
<div class="sidebar left-sidebar">
<?php
$leftsidebar = simple_fields_get_post_group_values($post->ID, "Left Sidebar", false, 2);
foreach ($leftsidebar as $value) {
?>
<aside>
<h2> <?php echo $value[1]; ?></h2>
<div>
<?php
if($value[2]):
if (function_exists('cforms_insert')){
echo cforms_insert(do_shortcode($value[2]));
} else {
echo do_shortcode($value[2]);
}
endif;
?>
</div>
</aside>
<?php } ?>
</div>
</div>
</code></pre>
<p>I did not build the site. And while I am proficient in pure HTML, I know little about PHP. Is this just a syntax issue that can be resolved with some quick fixes? Or do I need to go out and install a completely new theme (which scares the heck out of me)?</p>
| [
{
"answer_id": 355229,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 4,
"selected": true,
"text": "<p>welcome aboard. </p>\n\n<p>WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to <strong>your theme's</strong> <code>functions.php</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('wp-mediaelement');\n wp_deregister_style('wp-mediaelement');\n}\nadd_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n\n<p>PS. This code de-register mediaelements.js from all WordPress (with your current theme).</p>\n"
},
{
"answer_id": 409362,
"author": "Mahdi",
"author_id": 225629,
"author_profile": "https://wordpress.stackexchange.com/users/225629",
"pm_score": 0,
"selected": false,
"text": "<p>I just tested this method, by using this piece of code you will eliminate watching online option from users. The file will be automatically downloaded as somebody enters the page.</p>\n"
},
{
"answer_id": 413231,
"author": "MarkJ",
"author_id": 165181,
"author_profile": "https://wordpress.stackexchange.com/users/165181",
"pm_score": 0,
"selected": false,
"text": "<p>Serkan's answer removed only some mediaelement files for me.\nThis removed it completely:</p>\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('mediaelement');\n wp_deregister_style('mediaelement');\n }\n add_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n"
}
] | 2019/12/27 | [
"https://wordpress.stackexchange.com/questions/355267",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180257/"
] | Is this because of Wordpress, PHP, or the Theme? (or some combination)
A client of mine has a Wordpress site that's been working just fine for years, but recently started getting the following errors pulling up in it's sidebars:
Warning: Invalid argument supplied for foreach() in /wp-content/themes/epsilon/page-threecolumn.php on line 29
Been thinking it may have to do with upgrades to both Wordpress and PHP. Theme is no longer supported. Here is what the code looks like in that area:
```
<div class="col-234">
<div class="sidebar left-sidebar">
<?php
$leftsidebar = simple_fields_get_post_group_values($post->ID, "Left Sidebar", false, 2);
foreach ($leftsidebar as $value) {
?>
<aside>
<h2> <?php echo $value[1]; ?></h2>
<div>
<?php
if($value[2]):
if (function_exists('cforms_insert')){
echo cforms_insert(do_shortcode($value[2]));
} else {
echo do_shortcode($value[2]);
}
endif;
?>
</div>
</aside>
<?php } ?>
</div>
</div>
```
I did not build the site. And while I am proficient in pure HTML, I know little about PHP. Is this just a syntax issue that can be resolved with some quick fixes? Or do I need to go out and install a completely new theme (which scares the heck out of me)? | welcome aboard.
WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to **your theme's** `functions.php`
```php
function deregister_media_elements(){
wp_deregister_script('wp-mediaelement');
wp_deregister_style('wp-mediaelement');
}
add_action('wp_enqueue_scripts','deregister_media_elements');
```
PS. This code de-register mediaelements.js from all WordPress (with your current theme). |
355,347 | <p>I am not sure where exactly I navigate to add the analytics code once so it gets to all the WordPress pages.</p>
<p>Do I change the HTML manually or can I do this from WordPress somewhere?</p>
| [
{
"answer_id": 355229,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 4,
"selected": true,
"text": "<p>welcome aboard. </p>\n\n<p>WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to <strong>your theme's</strong> <code>functions.php</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('wp-mediaelement');\n wp_deregister_style('wp-mediaelement');\n}\nadd_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n\n<p>PS. This code de-register mediaelements.js from all WordPress (with your current theme).</p>\n"
},
{
"answer_id": 409362,
"author": "Mahdi",
"author_id": 225629,
"author_profile": "https://wordpress.stackexchange.com/users/225629",
"pm_score": 0,
"selected": false,
"text": "<p>I just tested this method, by using this piece of code you will eliminate watching online option from users. The file will be automatically downloaded as somebody enters the page.</p>\n"
},
{
"answer_id": 413231,
"author": "MarkJ",
"author_id": 165181,
"author_profile": "https://wordpress.stackexchange.com/users/165181",
"pm_score": 0,
"selected": false,
"text": "<p>Serkan's answer removed only some mediaelement files for me.\nThis removed it completely:</p>\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('mediaelement');\n wp_deregister_style('mediaelement');\n }\n add_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n"
}
] | 2019/12/29 | [
"https://wordpress.stackexchange.com/questions/355347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34846/"
] | I am not sure where exactly I navigate to add the analytics code once so it gets to all the WordPress pages.
Do I change the HTML manually or can I do this from WordPress somewhere? | welcome aboard.
WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to **your theme's** `functions.php`
```php
function deregister_media_elements(){
wp_deregister_script('wp-mediaelement');
wp_deregister_style('wp-mediaelement');
}
add_action('wp_enqueue_scripts','deregister_media_elements');
```
PS. This code de-register mediaelements.js from all WordPress (with your current theme). |
355,360 | <p>i created a dbdelta table but i cant seem to insert any data
here is my code
please help</p>
<pre><code>function lapizzeria_save_reservation() {
global $wpdb;
if(isset($_POST['reservation']) && $_POST['hidden'] =="1") {
$name =$_POST['name'];
$date =$_POST['date'];
$email =$_POST['email'];
$phone =$_POST['phone'];
$message =$_POST['message'];
$table = $wpdb->prefix . 'reservations';
$data = array(
'name' => $name,
'date' => $date,
'email' => $email,
'phone' => $phone,
'message' => $message
);
$format = array(
'%s',
'%s',
'%s',
'%s',
'%s'
);
$wpdb->insert($table, $data, $format);
}
}
add_action('init', 'lapizzeria_save_reservation');
</code></pre>
<p>here is the html</p>
<pre><code><form class="reservation-form" method="post">
<h2>Make a Reservation</h2>
<div class="field">
<input type="text" name="name" placeholder="Name" required>
</div>
<div class="field">
<input type="datetime-local" name="date" placeholder="Date" required>
</div>
<div class="field">
<input type="text" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="tel" name="phone" placeholder="Phone Number" required>
</div>
<div class="field">
<textarea name="message" placeholder="Message" requires></textarea>
</div>
<input type="submit" name="reservation" class="button" value="Send">
<input type="hidden" name="hidden" value="1">
</form>
</code></pre>
| [
{
"answer_id": 355229,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 4,
"selected": true,
"text": "<p>welcome aboard. </p>\n\n<p>WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to <strong>your theme's</strong> <code>functions.php</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('wp-mediaelement');\n wp_deregister_style('wp-mediaelement');\n}\nadd_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n\n<p>PS. This code de-register mediaelements.js from all WordPress (with your current theme).</p>\n"
},
{
"answer_id": 409362,
"author": "Mahdi",
"author_id": 225629,
"author_profile": "https://wordpress.stackexchange.com/users/225629",
"pm_score": 0,
"selected": false,
"text": "<p>I just tested this method, by using this piece of code you will eliminate watching online option from users. The file will be automatically downloaded as somebody enters the page.</p>\n"
},
{
"answer_id": 413231,
"author": "MarkJ",
"author_id": 165181,
"author_profile": "https://wordpress.stackexchange.com/users/165181",
"pm_score": 0,
"selected": false,
"text": "<p>Serkan's answer removed only some mediaelement files for me.\nThis removed it completely:</p>\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('mediaelement');\n wp_deregister_style('mediaelement');\n }\n add_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n"
}
] | 2019/12/29 | [
"https://wordpress.stackexchange.com/questions/355360",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180293/"
] | i created a dbdelta table but i cant seem to insert any data
here is my code
please help
```
function lapizzeria_save_reservation() {
global $wpdb;
if(isset($_POST['reservation']) && $_POST['hidden'] =="1") {
$name =$_POST['name'];
$date =$_POST['date'];
$email =$_POST['email'];
$phone =$_POST['phone'];
$message =$_POST['message'];
$table = $wpdb->prefix . 'reservations';
$data = array(
'name' => $name,
'date' => $date,
'email' => $email,
'phone' => $phone,
'message' => $message
);
$format = array(
'%s',
'%s',
'%s',
'%s',
'%s'
);
$wpdb->insert($table, $data, $format);
}
}
add_action('init', 'lapizzeria_save_reservation');
```
here is the html
```
<form class="reservation-form" method="post">
<h2>Make a Reservation</h2>
<div class="field">
<input type="text" name="name" placeholder="Name" required>
</div>
<div class="field">
<input type="datetime-local" name="date" placeholder="Date" required>
</div>
<div class="field">
<input type="text" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="tel" name="phone" placeholder="Phone Number" required>
</div>
<div class="field">
<textarea name="message" placeholder="Message" requires></textarea>
</div>
<input type="submit" name="reservation" class="button" value="Send">
<input type="hidden" name="hidden" value="1">
</form>
``` | welcome aboard.
WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to **your theme's** `functions.php`
```php
function deregister_media_elements(){
wp_deregister_script('wp-mediaelement');
wp_deregister_style('wp-mediaelement');
}
add_action('wp_enqueue_scripts','deregister_media_elements');
```
PS. This code de-register mediaelements.js from all WordPress (with your current theme). |
355,392 | <p>I've been breaking my head on this one. I have a child theme and made changes to the <code>style.css</code> document. These changes did not show up in the reload of the page because there is no mention of version in the stylesheet declaration of this file. </p>
<p>I have found out that <code>style.css</code> is loaded as a foundation of the theme and that the version number in the header of <code>style.css</code> is supposed to show up, but it doesn't. I've tried the deregister, dequeue and requeue options that I found online, but still no go.</p>
<p>I have made a work around by queueing another css file for which I have added versioning based on the modification date of the file, but I am curious if others have seen this issue and have a proper solution.</p>
| [
{
"answer_id": 355229,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 4,
"selected": true,
"text": "<p>welcome aboard. </p>\n\n<p>WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to <strong>your theme's</strong> <code>functions.php</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('wp-mediaelement');\n wp_deregister_style('wp-mediaelement');\n}\nadd_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n\n<p>PS. This code de-register mediaelements.js from all WordPress (with your current theme).</p>\n"
},
{
"answer_id": 409362,
"author": "Mahdi",
"author_id": 225629,
"author_profile": "https://wordpress.stackexchange.com/users/225629",
"pm_score": 0,
"selected": false,
"text": "<p>I just tested this method, by using this piece of code you will eliminate watching online option from users. The file will be automatically downloaded as somebody enters the page.</p>\n"
},
{
"answer_id": 413231,
"author": "MarkJ",
"author_id": 165181,
"author_profile": "https://wordpress.stackexchange.com/users/165181",
"pm_score": 0,
"selected": false,
"text": "<p>Serkan's answer removed only some mediaelement files for me.\nThis removed it completely:</p>\n<pre class=\"lang-php prettyprint-override\"><code> function deregister_media_elements(){\n wp_deregister_script('mediaelement');\n wp_deregister_style('mediaelement');\n }\n add_action('wp_enqueue_scripts','deregister_media_elements');\n</code></pre>\n"
}
] | 2019/12/30 | [
"https://wordpress.stackexchange.com/questions/355392",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180003/"
] | I've been breaking my head on this one. I have a child theme and made changes to the `style.css` document. These changes did not show up in the reload of the page because there is no mention of version in the stylesheet declaration of this file.
I have found out that `style.css` is loaded as a foundation of the theme and that the version number in the header of `style.css` is supposed to show up, but it doesn't. I've tried the deregister, dequeue and requeue options that I found online, but still no go.
I have made a work around by queueing another css file for which I have added versioning based on the modification date of the file, but I am curious if others have seen this issue and have a proper solution. | welcome aboard.
WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to **your theme's** `functions.php`
```php
function deregister_media_elements(){
wp_deregister_script('wp-mediaelement');
wp_deregister_style('wp-mediaelement');
}
add_action('wp_enqueue_scripts','deregister_media_elements');
```
PS. This code de-register mediaelements.js from all WordPress (with your current theme). |
355,440 | <p>I have the code,
<a href="https://i.stack.imgur.com/TAOEb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TAOEb.png" alt="enter image description here"></a></p>
<pre><code>/*
* Add a metabox
* I hope you're familiar with add_meta_box() function, so, nothing new for you here
*/
add_action( 'admin_menu', 'rudr_metabox_for_select2_cat' );
function rudr_metabox_for_select2_cat() {
add_meta_box( 'rudr_select2', 'Tune Category', 'rudr_display_select2_cat_metabox', 'post', 'side', 'high' );
}
/*
* Display the fields inside it
*/
function rudr_display_select2_cat_metabox( $post_object ) {
// I decided to write all the metabox html into a variable and then echo it at the end
$html = '';
// always array because we have added [] to our <select> name attribute
$appended_cat = get_post_meta( $post_object->ID, 'rudr_select2_cat',true );
/*
* It will be just a multiple select for tags without AJAX search
* If no tags found - do not display anything
* hide_empty=0 means to show tags not attached to any posts
*/
if( $cats = get_terms( 'category', 'hide_empty=0' ) ) {
$html .= '<p><select id="rudr_select2_cat" name="rudr_select2_cat[]" single="single" style="width:99%;max-width:25em;">';
foreach( $cats as $cat ) {
$selected = ( is_array( $appended_cat ) && in_array( $cat->term_id, $appended_cat ) ) ? ' selected="selected"' : '';
$html .= '<option value="' . $cat->term_id . '"' . $selected . '>' . $cat->name . '</option>';
}
$html .= '<select></p>';
}
echo $html;
}
add_action( 'wp_ajax_mishagetcat', 'rudr_get_cat_ajax_callback' ); // wp_ajax_{action}
function rudr_get_cat_ajax_callback(){
// we will pass post IDs and titles to this array
$return = array();
$cat = get_terms( array('taxonomy' => 'category','search'=> $_GET['q'],'ignore_sticky_posts' => 1,));
foreach ( $cat as $cat ) {
// shorten the title a little
$title = ( mb_strlen( $cat->name ) > 50 ) ? mb_substr( $cat->name, 0, 49 ) . '...' : $cat->name;
$return[] = array( $cat->term_id, $title ); // array( Post ID, Post Title )
}
echo json_encode( $return );
die;
}
//auto_save
add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );
function rudr_save_metaboxdata( $post_id, $post ) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
// if post type is different from our selected one, do nothing
if ( $post->post_type == 'post' ) {
if( isset( $_POST['rudr_select2_cat'] ) )
update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );
else
delete_post_meta( $post_id, 'rudr_select2_cat' );
if( isset( $_POST['rudr_select2_tags'] ) )
update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );
else
delete_post_meta( $post_id, 'rudr_select2_tags' );
}
return $post_id;
}
//add_script_&_stylesheet
add_action( 'admin_enqueue_scripts', 'rudr_select2_enqueue' );
function rudr_select2_enqueue(){
wp_enqueue_style('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' );
wp_enqueue_script('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js', array('jquery') );
// please create also an empty JS file in your theme directory and include it too
wp_enqueue_script('mycustom', get_template_directory_uri() . '/css/mycustom.js', array( 'jquery', 'select2' ) );
}
</code></pre>
<p><a href="https://i.stack.imgur.com/vkZMN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vkZMN.png" alt="enter image description here"></a>
But Showing only deafult category.</p>
| [
{
"answer_id": 355441,
"author": "Pradipta Sarkar",
"author_id": 178446,
"author_profile": "https://wordpress.stackexchange.com/users/178446",
"pm_score": 2,
"selected": true,
"text": "<p>First of all you saved the the terms value in a post meta table and not following the wordpress conventional method. </p>\n\n<p>To make it connect with default category with that post you need to modify your <code>save_post</code> action. Check the modified code. </p>\n\n<pre><code>add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );\nfunction rudr_save_metaboxdata( $post_id, $post ) {\n\n if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;\n\n // if post type is different from our selected one, do nothing\n if ( $post->post_type == 'post' ) {\n if( isset( $_POST['rudr_select2_cat'] ) )\n {\n wp_set_object_terms($post_id, $_POST['rudr_select2_cat', 'category', false) ;\n update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );\n }\n else\n delete_post_meta( $post_id, 'rudr_select2_cat' );\n if( isset( $_POST['rudr_select2_tags'] ) )\n update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );\n else\n delete_post_meta( $post_id, 'rudr_select2_tags' );\n }\n return $post_id;\n}\n</code></pre>\n\n<p>Please check <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">wp_set_object_terms()</a> for reference. </p>\n"
},
{
"answer_id": 355449,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to save your Tune Category as deafult category, you have to use <code>wp_set_post_terms()</code> with <code>update_post_meta()</code>.</p>\n\n<pre><code>add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );\nfunction rudr_save_metaboxdata( $post_id, $post ) {\n\n if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;\n\n // if post type is different from our selected one, do nothing\n if ( $post->post_type == 'post' ) {\n if( isset( $_POST['rudr_select2_cat'] ) )\n {\n update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );\n wp_set_post_terms($post_id, $_POST['rudr_select2_cat'], 'category', FALSE);\n }\n else\n {\n delete_post_meta( $post_id, 'rudr_select2_cat' );\n wp_set_post_terms($post_id,'', 'category', FALSE);\n }\n\n if( isset( $_POST['rudr_select2_tags'] ) )\n update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );\n else\n delete_post_meta( $post_id, 'rudr_select2_tags' );\n }\n return $post_id;\n}\n</code></pre>\n\n<p>I have tested and it is working fine: <a href=\"https://prnt.sc/qhubbd\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubbd</a> , <a href=\"https://prnt.sc/qhubjw\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubjw</a> , <a href=\"https://prnt.sc/qhubf2\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubf2</a> , <a href=\"https://prnt.sc/qhubha\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubha</a></p>\n"
}
] | 2019/12/31 | [
"https://wordpress.stackexchange.com/questions/355440",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180205/"
] | I have the code,
[](https://i.stack.imgur.com/TAOEb.png)
```
/*
* Add a metabox
* I hope you're familiar with add_meta_box() function, so, nothing new for you here
*/
add_action( 'admin_menu', 'rudr_metabox_for_select2_cat' );
function rudr_metabox_for_select2_cat() {
add_meta_box( 'rudr_select2', 'Tune Category', 'rudr_display_select2_cat_metabox', 'post', 'side', 'high' );
}
/*
* Display the fields inside it
*/
function rudr_display_select2_cat_metabox( $post_object ) {
// I decided to write all the metabox html into a variable and then echo it at the end
$html = '';
// always array because we have added [] to our <select> name attribute
$appended_cat = get_post_meta( $post_object->ID, 'rudr_select2_cat',true );
/*
* It will be just a multiple select for tags without AJAX search
* If no tags found - do not display anything
* hide_empty=0 means to show tags not attached to any posts
*/
if( $cats = get_terms( 'category', 'hide_empty=0' ) ) {
$html .= '<p><select id="rudr_select2_cat" name="rudr_select2_cat[]" single="single" style="width:99%;max-width:25em;">';
foreach( $cats as $cat ) {
$selected = ( is_array( $appended_cat ) && in_array( $cat->term_id, $appended_cat ) ) ? ' selected="selected"' : '';
$html .= '<option value="' . $cat->term_id . '"' . $selected . '>' . $cat->name . '</option>';
}
$html .= '<select></p>';
}
echo $html;
}
add_action( 'wp_ajax_mishagetcat', 'rudr_get_cat_ajax_callback' ); // wp_ajax_{action}
function rudr_get_cat_ajax_callback(){
// we will pass post IDs and titles to this array
$return = array();
$cat = get_terms( array('taxonomy' => 'category','search'=> $_GET['q'],'ignore_sticky_posts' => 1,));
foreach ( $cat as $cat ) {
// shorten the title a little
$title = ( mb_strlen( $cat->name ) > 50 ) ? mb_substr( $cat->name, 0, 49 ) . '...' : $cat->name;
$return[] = array( $cat->term_id, $title ); // array( Post ID, Post Title )
}
echo json_encode( $return );
die;
}
//auto_save
add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );
function rudr_save_metaboxdata( $post_id, $post ) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
// if post type is different from our selected one, do nothing
if ( $post->post_type == 'post' ) {
if( isset( $_POST['rudr_select2_cat'] ) )
update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );
else
delete_post_meta( $post_id, 'rudr_select2_cat' );
if( isset( $_POST['rudr_select2_tags'] ) )
update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );
else
delete_post_meta( $post_id, 'rudr_select2_tags' );
}
return $post_id;
}
//add_script_&_stylesheet
add_action( 'admin_enqueue_scripts', 'rudr_select2_enqueue' );
function rudr_select2_enqueue(){
wp_enqueue_style('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' );
wp_enqueue_script('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js', array('jquery') );
// please create also an empty JS file in your theme directory and include it too
wp_enqueue_script('mycustom', get_template_directory_uri() . '/css/mycustom.js', array( 'jquery', 'select2' ) );
}
```
[](https://i.stack.imgur.com/vkZMN.png)
But Showing only deafult category. | First of all you saved the the terms value in a post meta table and not following the wordpress conventional method.
To make it connect with default category with that post you need to modify your `save_post` action. Check the modified code.
```
add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );
function rudr_save_metaboxdata( $post_id, $post ) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
// if post type is different from our selected one, do nothing
if ( $post->post_type == 'post' ) {
if( isset( $_POST['rudr_select2_cat'] ) )
{
wp_set_object_terms($post_id, $_POST['rudr_select2_cat', 'category', false) ;
update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );
}
else
delete_post_meta( $post_id, 'rudr_select2_cat' );
if( isset( $_POST['rudr_select2_tags'] ) )
update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );
else
delete_post_meta( $post_id, 'rudr_select2_tags' );
}
return $post_id;
}
```
Please check [wp\_set\_object\_terms()](https://codex.wordpress.org/Function_Reference/wp_set_object_terms) for reference. |
355,446 | <p>I am using WP forms and want to have a dropdown menu where users can select their timezone. I found a list that I could hardcode into the dropdown but I read somewhere that this would be a bad idea because of daylight savings time. Not sure if that is the case.</p>
<p>Anyway, if anyone has some suggestions for this I would really appreciate it. Not sure if it is possible also to automatically detect the users timezone and store it in hidden field. This would be a better user experience. </p>
| [
{
"answer_id": 355441,
"author": "Pradipta Sarkar",
"author_id": 178446,
"author_profile": "https://wordpress.stackexchange.com/users/178446",
"pm_score": 2,
"selected": true,
"text": "<p>First of all you saved the the terms value in a post meta table and not following the wordpress conventional method. </p>\n\n<p>To make it connect with default category with that post you need to modify your <code>save_post</code> action. Check the modified code. </p>\n\n<pre><code>add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );\nfunction rudr_save_metaboxdata( $post_id, $post ) {\n\n if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;\n\n // if post type is different from our selected one, do nothing\n if ( $post->post_type == 'post' ) {\n if( isset( $_POST['rudr_select2_cat'] ) )\n {\n wp_set_object_terms($post_id, $_POST['rudr_select2_cat', 'category', false) ;\n update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );\n }\n else\n delete_post_meta( $post_id, 'rudr_select2_cat' );\n if( isset( $_POST['rudr_select2_tags'] ) )\n update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );\n else\n delete_post_meta( $post_id, 'rudr_select2_tags' );\n }\n return $post_id;\n}\n</code></pre>\n\n<p>Please check <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">wp_set_object_terms()</a> for reference. </p>\n"
},
{
"answer_id": 355449,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to save your Tune Category as deafult category, you have to use <code>wp_set_post_terms()</code> with <code>update_post_meta()</code>.</p>\n\n<pre><code>add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );\nfunction rudr_save_metaboxdata( $post_id, $post ) {\n\n if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;\n\n // if post type is different from our selected one, do nothing\n if ( $post->post_type == 'post' ) {\n if( isset( $_POST['rudr_select2_cat'] ) )\n {\n update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );\n wp_set_post_terms($post_id, $_POST['rudr_select2_cat'], 'category', FALSE);\n }\n else\n {\n delete_post_meta( $post_id, 'rudr_select2_cat' );\n wp_set_post_terms($post_id,'', 'category', FALSE);\n }\n\n if( isset( $_POST['rudr_select2_tags'] ) )\n update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );\n else\n delete_post_meta( $post_id, 'rudr_select2_tags' );\n }\n return $post_id;\n}\n</code></pre>\n\n<p>I have tested and it is working fine: <a href=\"https://prnt.sc/qhubbd\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubbd</a> , <a href=\"https://prnt.sc/qhubjw\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubjw</a> , <a href=\"https://prnt.sc/qhubf2\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubf2</a> , <a href=\"https://prnt.sc/qhubha\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubha</a></p>\n"
}
] | 2019/12/31 | [
"https://wordpress.stackexchange.com/questions/355446",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165412/"
] | I am using WP forms and want to have a dropdown menu where users can select their timezone. I found a list that I could hardcode into the dropdown but I read somewhere that this would be a bad idea because of daylight savings time. Not sure if that is the case.
Anyway, if anyone has some suggestions for this I would really appreciate it. Not sure if it is possible also to automatically detect the users timezone and store it in hidden field. This would be a better user experience. | First of all you saved the the terms value in a post meta table and not following the wordpress conventional method.
To make it connect with default category with that post you need to modify your `save_post` action. Check the modified code.
```
add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );
function rudr_save_metaboxdata( $post_id, $post ) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
// if post type is different from our selected one, do nothing
if ( $post->post_type == 'post' ) {
if( isset( $_POST['rudr_select2_cat'] ) )
{
wp_set_object_terms($post_id, $_POST['rudr_select2_cat', 'category', false) ;
update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );
}
else
delete_post_meta( $post_id, 'rudr_select2_cat' );
if( isset( $_POST['rudr_select2_tags'] ) )
update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );
else
delete_post_meta( $post_id, 'rudr_select2_tags' );
}
return $post_id;
}
```
Please check [wp\_set\_object\_terms()](https://codex.wordpress.org/Function_Reference/wp_set_object_terms) for reference. |
355,448 | <p>I have a custom post type called <code>produce</code> set up in WordPress and a custom taxonomy called <code>produce_category</code>.</p>
<p>The URL format for posts in this custom post type is in this format <code>http://mywebsite/produce/%produce_category%/%postname%/</code>. Of course <code>%produce_category%</code> and <code>%postname%</code> get substituted accordingly, a working example url would be <code>http://mywebsite/produce/fruits-and-vegetables/avocado</code>.</p>
<p>What I would like to do is show the produce_category custom taxonomy archive if a user visits <code>http://mywebsite/produce/%produce_category%</code>, without specifying post name at the end, e.g <code>http://mywebsite/produce/fruits-and-vegetables</code> to show all produce in fruits-and-vegetables produce_category.</p>
<p>Besides that when a user visits <code>http://mywebsite/produce/</code> I would like to show all the produce archive. EDIT: I have this working now.</p>
<p>I know how to create the archive pages totally fine and have no problem with that. I am stuck at creating permalinks. When I visit <code>http://mywebsite/produce/%produce_category%</code> I get a 404 error.</p>
<p>I'm looking for advise on the best way to implement this. Currently I am using <strong>Custom Post Type Permalinks</strong> and <strong>CPTUI</strong>.</p>
<p>The CPTUI custom taxonomy settings interface does not allow me to have a blank in the custom rewrite slug. It defaults to the custom taxonomy slug, <code>produce_category</code>, when I don't fill in anything.
<a href="https://i.stack.imgur.com/sO0l5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sO0l5.png" alt="enter image description here"></a></p>
<p>This gives the front-side produce_category taxonomy archive url as <code>http://mywebsite/produce/produce_category/%produce_category%/</code> e.g. <code>http://mywebsite/produce/produce_category/fish-and-seafood/</code> when what I want for the archive is <code>http://mywebsite/produce/fish-and-seafood/</code>.</p>
<p>Please help with suggestion on the best way I can achieve the custom taxonomy url.</p>
<p>Thank you all.</p>
| [
{
"answer_id": 355441,
"author": "Pradipta Sarkar",
"author_id": 178446,
"author_profile": "https://wordpress.stackexchange.com/users/178446",
"pm_score": 2,
"selected": true,
"text": "<p>First of all you saved the the terms value in a post meta table and not following the wordpress conventional method. </p>\n\n<p>To make it connect with default category with that post you need to modify your <code>save_post</code> action. Check the modified code. </p>\n\n<pre><code>add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );\nfunction rudr_save_metaboxdata( $post_id, $post ) {\n\n if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;\n\n // if post type is different from our selected one, do nothing\n if ( $post->post_type == 'post' ) {\n if( isset( $_POST['rudr_select2_cat'] ) )\n {\n wp_set_object_terms($post_id, $_POST['rudr_select2_cat', 'category', false) ;\n update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );\n }\n else\n delete_post_meta( $post_id, 'rudr_select2_cat' );\n if( isset( $_POST['rudr_select2_tags'] ) )\n update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );\n else\n delete_post_meta( $post_id, 'rudr_select2_tags' );\n }\n return $post_id;\n}\n</code></pre>\n\n<p>Please check <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">wp_set_object_terms()</a> for reference. </p>\n"
},
{
"answer_id": 355449,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to save your Tune Category as deafult category, you have to use <code>wp_set_post_terms()</code> with <code>update_post_meta()</code>.</p>\n\n<pre><code>add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );\nfunction rudr_save_metaboxdata( $post_id, $post ) {\n\n if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;\n\n // if post type is different from our selected one, do nothing\n if ( $post->post_type == 'post' ) {\n if( isset( $_POST['rudr_select2_cat'] ) )\n {\n update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );\n wp_set_post_terms($post_id, $_POST['rudr_select2_cat'], 'category', FALSE);\n }\n else\n {\n delete_post_meta( $post_id, 'rudr_select2_cat' );\n wp_set_post_terms($post_id,'', 'category', FALSE);\n }\n\n if( isset( $_POST['rudr_select2_tags'] ) )\n update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );\n else\n delete_post_meta( $post_id, 'rudr_select2_tags' );\n }\n return $post_id;\n}\n</code></pre>\n\n<p>I have tested and it is working fine: <a href=\"https://prnt.sc/qhubbd\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubbd</a> , <a href=\"https://prnt.sc/qhubjw\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubjw</a> , <a href=\"https://prnt.sc/qhubf2\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubf2</a> , <a href=\"https://prnt.sc/qhubha\" rel=\"nofollow noreferrer\">https://prnt.sc/qhubha</a></p>\n"
}
] | 2019/12/31 | [
"https://wordpress.stackexchange.com/questions/355448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118073/"
] | I have a custom post type called `produce` set up in WordPress and a custom taxonomy called `produce_category`.
The URL format for posts in this custom post type is in this format `http://mywebsite/produce/%produce_category%/%postname%/`. Of course `%produce_category%` and `%postname%` get substituted accordingly, a working example url would be `http://mywebsite/produce/fruits-and-vegetables/avocado`.
What I would like to do is show the produce\_category custom taxonomy archive if a user visits `http://mywebsite/produce/%produce_category%`, without specifying post name at the end, e.g `http://mywebsite/produce/fruits-and-vegetables` to show all produce in fruits-and-vegetables produce\_category.
Besides that when a user visits `http://mywebsite/produce/` I would like to show all the produce archive. EDIT: I have this working now.
I know how to create the archive pages totally fine and have no problem with that. I am stuck at creating permalinks. When I visit `http://mywebsite/produce/%produce_category%` I get a 404 error.
I'm looking for advise on the best way to implement this. Currently I am using **Custom Post Type Permalinks** and **CPTUI**.
The CPTUI custom taxonomy settings interface does not allow me to have a blank in the custom rewrite slug. It defaults to the custom taxonomy slug, `produce_category`, when I don't fill in anything.
[](https://i.stack.imgur.com/sO0l5.png)
This gives the front-side produce\_category taxonomy archive url as `http://mywebsite/produce/produce_category/%produce_category%/` e.g. `http://mywebsite/produce/produce_category/fish-and-seafood/` when what I want for the archive is `http://mywebsite/produce/fish-and-seafood/`.
Please help with suggestion on the best way I can achieve the custom taxonomy url.
Thank you all. | First of all you saved the the terms value in a post meta table and not following the wordpress conventional method.
To make it connect with default category with that post you need to modify your `save_post` action. Check the modified code.
```
add_action( 'save_post', 'rudr_save_metaboxdata', 10, 2 );
function rudr_save_metaboxdata( $post_id, $post ) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
// if post type is different from our selected one, do nothing
if ( $post->post_type == 'post' ) {
if( isset( $_POST['rudr_select2_cat'] ) )
{
wp_set_object_terms($post_id, $_POST['rudr_select2_cat', 'category', false) ;
update_post_meta( $post_id, 'rudr_select2_cat', $_POST['rudr_select2_cat'] );
}
else
delete_post_meta( $post_id, 'rudr_select2_cat' );
if( isset( $_POST['rudr_select2_tags'] ) )
update_post_meta( $post_id, 'rudr_select2_tags', $_POST['rudr_select2_tags'] );
else
delete_post_meta( $post_id, 'rudr_select2_tags' );
}
return $post_id;
}
```
Please check [wp\_set\_object\_terms()](https://codex.wordpress.org/Function_Reference/wp_set_object_terms) for reference. |
355,456 | <p>I have a function to show theme details and want to put it in a sentence.
Like: The "theme" developed by "author". And it will contain links.</p>
<p>I tried printf, did get the correct result.</p>
<pre><code> function logbook_info() {
$theme_logbook = wp_get_theme();
echo esc_html( $theme_logbook->get( 'TextDomain' ) );
echo esc_html( $theme_logbook->get( 'ThemeURI' ) );
echo esc_html( $theme_logbook->get( 'AuthorURI' ) );
}
add_action( 'logbookinfo', 'logbook_info' );
</code></pre>
| [
{
"answer_id": 355457,
"author": "Pradipta Sarkar",
"author_id": 178446,
"author_profile": "https://wordpress.stackexchange.com/users/178446",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function logbook_info() {\n $theme_logbook = wp_get_theme();\n echo 'The'.esc_html( $theme_logbook->get( 'TextDomain' ) ). 'Developed by '.\n esc_html( $theme_logbook->get( 'AuthorURI' ) );\n}\n\nadd_action( 'logbookinfo', 'logbook_info' );\n</code></pre>\n\n<p>Try this. </p>\n"
},
{
"answer_id": 355458,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 1,
"selected": false,
"text": "<p>You can use below code to display theme detail sentence. I have use <code>wp_footer</code> action,You can change hook as per your requirement.</p>\n\n<pre><code>function logbook_info() {\n $theme_logbook = wp_get_theme();\n $theme_name = esc_html( $theme_logbook->get( 'Name' ) );\n $theme_uri = esc_html( $theme_logbook->get( 'ThemeURI' ) );\n $theme_author = esc_html( $theme_logbook->get( 'Author' ) );\n $theme_author_uri = esc_html( $theme_logbook->get( 'AuthorURI' ) );\n\n $theme_html = '<a href=\"'.$theme_uri.'\">'.$theme_name.'</a>';\n $author_html = '<a href=\"'.$theme_author_uri.'\">'.$theme_author.'</a>';\n\n echo \"The \".$theme_html.\" developed by \".$author_html;\n}\nadd_action( 'wp_footer', 'logbook_info' );\n</code></pre>\n\n<p>It will add theme detail in footer : <a href=\"https://prnt.sc/qhva3o\" rel=\"nofollow noreferrer\">https://prnt.sc/qhva3o</a></p>\n"
}
] | 2019/12/31 | [
"https://wordpress.stackexchange.com/questions/355456",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180399/"
] | I have a function to show theme details and want to put it in a sentence.
Like: The "theme" developed by "author". And it will contain links.
I tried printf, did get the correct result.
```
function logbook_info() {
$theme_logbook = wp_get_theme();
echo esc_html( $theme_logbook->get( 'TextDomain' ) );
echo esc_html( $theme_logbook->get( 'ThemeURI' ) );
echo esc_html( $theme_logbook->get( 'AuthorURI' ) );
}
add_action( 'logbookinfo', 'logbook_info' );
``` | You can use below code to display theme detail sentence. I have use `wp_footer` action,You can change hook as per your requirement.
```
function logbook_info() {
$theme_logbook = wp_get_theme();
$theme_name = esc_html( $theme_logbook->get( 'Name' ) );
$theme_uri = esc_html( $theme_logbook->get( 'ThemeURI' ) );
$theme_author = esc_html( $theme_logbook->get( 'Author' ) );
$theme_author_uri = esc_html( $theme_logbook->get( 'AuthorURI' ) );
$theme_html = '<a href="'.$theme_uri.'">'.$theme_name.'</a>';
$author_html = '<a href="'.$theme_author_uri.'">'.$theme_author.'</a>';
echo "The ".$theme_html." developed by ".$author_html;
}
add_action( 'wp_footer', 'logbook_info' );
```
It will add theme detail in footer : <https://prnt.sc/qhva3o> |
355,462 | <p>I am trying to create a website with wordpress and I want to change the text value of the submit button (included in the pictures). When I change its' text value while inspecting the element, it changes successfully, but when I do it with custom CSS, it fails. What code should I write to the custom CSS file to successfully change the buttons' text value?</p>
<p><a href="https://i.stack.imgur.com/odVud.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/odVud.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Phubm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Phubm.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 355457,
"author": "Pradipta Sarkar",
"author_id": 178446,
"author_profile": "https://wordpress.stackexchange.com/users/178446",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function logbook_info() {\n $theme_logbook = wp_get_theme();\n echo 'The'.esc_html( $theme_logbook->get( 'TextDomain' ) ). 'Developed by '.\n esc_html( $theme_logbook->get( 'AuthorURI' ) );\n}\n\nadd_action( 'logbookinfo', 'logbook_info' );\n</code></pre>\n\n<p>Try this. </p>\n"
},
{
"answer_id": 355458,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 1,
"selected": false,
"text": "<p>You can use below code to display theme detail sentence. I have use <code>wp_footer</code> action,You can change hook as per your requirement.</p>\n\n<pre><code>function logbook_info() {\n $theme_logbook = wp_get_theme();\n $theme_name = esc_html( $theme_logbook->get( 'Name' ) );\n $theme_uri = esc_html( $theme_logbook->get( 'ThemeURI' ) );\n $theme_author = esc_html( $theme_logbook->get( 'Author' ) );\n $theme_author_uri = esc_html( $theme_logbook->get( 'AuthorURI' ) );\n\n $theme_html = '<a href=\"'.$theme_uri.'\">'.$theme_name.'</a>';\n $author_html = '<a href=\"'.$theme_author_uri.'\">'.$theme_author.'</a>';\n\n echo \"The \".$theme_html.\" developed by \".$author_html;\n}\nadd_action( 'wp_footer', 'logbook_info' );\n</code></pre>\n\n<p>It will add theme detail in footer : <a href=\"https://prnt.sc/qhva3o\" rel=\"nofollow noreferrer\">https://prnt.sc/qhva3o</a></p>\n"
}
] | 2019/12/31 | [
"https://wordpress.stackexchange.com/questions/355462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180406/"
] | I am trying to create a website with wordpress and I want to change the text value of the submit button (included in the pictures). When I change its' text value while inspecting the element, it changes successfully, but when I do it with custom CSS, it fails. What code should I write to the custom CSS file to successfully change the buttons' text value?
[](https://i.stack.imgur.com/odVud.png)
[](https://i.stack.imgur.com/Phubm.png) | You can use below code to display theme detail sentence. I have use `wp_footer` action,You can change hook as per your requirement.
```
function logbook_info() {
$theme_logbook = wp_get_theme();
$theme_name = esc_html( $theme_logbook->get( 'Name' ) );
$theme_uri = esc_html( $theme_logbook->get( 'ThemeURI' ) );
$theme_author = esc_html( $theme_logbook->get( 'Author' ) );
$theme_author_uri = esc_html( $theme_logbook->get( 'AuthorURI' ) );
$theme_html = '<a href="'.$theme_uri.'">'.$theme_name.'</a>';
$author_html = '<a href="'.$theme_author_uri.'">'.$theme_author.'</a>';
echo "The ".$theme_html." developed by ".$author_html;
}
add_action( 'wp_footer', 'logbook_info' );
```
It will add theme detail in footer : <https://prnt.sc/qhva3o> |
355,472 | <p>I am struggling to load translation in JavaScript for my simple plugin. Translation works for PHP, but not in JS. What seems to be the problem, how can I debug this? </p>
<ol>
<li><p>I have loaded text domain in my plugin method and this works ok. My text domain is <code>instantsearch</code>, locale for my language is <code>hr</code></p>
<pre><code>load_plugin_textdomain('instantsearch', FALSE, basename( dirname( __FILE__ ) ) . '/languages/'); // returns true
var_dump(__('No results', 'instantsearch')); // This shows correct translation for my language
</code></pre></li>
<li><p>I have generated .json file with WP CLI</p>
<pre><code>wp i18n make-json languages/
</code></pre></li>
<li><p>This gives me new file <code>/myplugin/languages/instantsearch-hr-hash.json</code>. My JS file is <code>assets/instant-search.js</code> and somewhere I have read that I need to manually rename that hash. I just copied that file two times and renamed them to the following just to try it out, so something out of those 3 should be working :) </p>
<pre><code>instantsearch-hr-47626afcca1bc179bc9eedb6abdc01ff.json
instantsearch-hr-instant-search.json
instantsearch-hr-instantsearch.json
</code></pre></li>
<li><p>I have registered the script for translation </p>
<pre><code>wp_register_script('instant-search', plugins_url('assets/instant-search.js', __FILE__), array('jquery', 'wp-i18n'), false, true);
wp_enqueue_script('instant-search');
wp_set_script_translations('instant-search', 'instantsearch', plugins_url('languages', __FILE__));
</code></pre></li>
<li><p>In the script at the very top I have tried this, but it doesn't give me translation like in PHP, it just shows english default string</p>
<pre><code>console.log(wp.i18n.__('No results', 'instantsearch'));
</code></pre></li>
<li><p>Here is example of json </p>
<pre><code>{"translation-revision-date":"2019-12-31 13:41+0100","generator":"WP-CLI\/2.4.0","source":"assets\/instant-search.js","domain":"messages","locale_data":{"messages":{"":{"domain":"messages","lang":"hr","plural-forms":"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);"},"No results":["Nema prona\u0111enih rezultata"]}}}
</code></pre></li>
<li><p>I know I can use <code>wp_localize_script()</code> to move string from PHP to JS but from WP 5.* we should be able to do it </p></li>
</ol>
| [
{
"answer_id": 365613,
"author": "Josiah Sprague",
"author_id": 21290,
"author_profile": "https://wordpress.stackexchange.com/users/21290",
"pm_score": 2,
"selected": false,
"text": "<p>I was having the same problem and this is how I solved it:</p>\n\n<p>First, the generated JSON file has some errors. You need to update where it says <code>messages</code> with your text domain. There are three places where that needs to be changed. I also had to change the <code>lang</code> attribute to be all lowercase with a dash. Here are the fields I changed:</p>\n\n<pre><code>{\n \"domain\": \"my-text-domain\",\n \"locale_data\": {\n \"my-text-domain\": { // Instead of \"messages\"\n \"\": {\n \"domain\": \"my-text-domain\",\n \"lang\": \"es-es\"\n },\n ...\n }\n }\n}\n\n</code></pre>\n\n<p>Second, the file name with the md5 hash tends to have the wrong md5 hash, so it's best to rename the file to <code>{domain}-{locale}-{script-name}.json</code>, so mine became <code>my-text-domain-es_ES-my-script-name.js</code>.</p>\n\n<p>Third, the <code>wp_set_script_translations</code> function needs to be called with the right path, and attached to the right hook. This is what I had to do, since I was localizing an admin-side script:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function enqueue_scripts() {\n wp_set_script_translations( 'script-name', 'my-text-domain', plugin_dir_path( dirname(__FILE__) ) . 'languages' );\n}\nadd_action( 'admin_enqueue_scripts', 'enqueue_scripts' );\n</code></pre>\n\n<p>Try echoing out the value of <code>plugin_dir_path( dirname(__FILE__) ) . 'languages'</code> to make sure you're getting the path where your translation files are.</p>\n\n<p>Once I sorted out all of these little details, my translations started working, so I hope this helps someone else!</p>\n"
},
{
"answer_id": 372478,
"author": "Kostiantyn Petlia",
"author_id": 104932,
"author_profile": "https://wordpress.stackexchange.com/users/104932",
"pm_score": 0,
"selected": false,
"text": "<p>I'll leave it here. Perhaps it will help someone. I had the same issue. I did all steps and all looked working, but in JS <code>__('Hello world', 'textdomain');</code> didn't work.</p>\n<p>There are a lot of recommendations about the JSON file for example to use 'nl' instead 'nl_NL', etc. For today (2020.08.06) you shouldn't change a json-file in any way except its name as <code>custom_dir/{domain}-{locale}-{handle}.json</code>.</p>\n<p>The base steps:</p>\n<ol>\n<li>PHP code:</li>\n</ol>\n<pre><code>load_theme_textdomain( 'textdomain', get_template_directory() . '/languages' );\n// ...\nwp_enqueue_script( 'scripts', asset_url( 'js/app.js' ), [ 'jquery', 'wp-i18n' ], null, true );\nwp_set_script_translations( 'scripts', 'textdomain', get_template_directory() .'/languages/js' );\n</code></pre>\n<ol start=\"2\">\n<li><p>I use the Poedit application for creating & translating the <code>nl_NL.po</code> file.</p>\n</li>\n<li><p>With WP-CLI I generate <code>wp i18n make-json ./languages ./languages/js --no-purge --pretty-print</code> a json-file and I reneme it to <code>./languages/js/textdomain-nl_NL-scripts.json</code>.</p>\n</li>\n</ol>\n<p><strong>The essential thing:</strong>\nThe author's mistake is <code>plugins_url('languages', __FILE__)</code> in <code>wp_set_script_translations();</code>. My mistake was a simple <code>get_template_directory_uri()</code> instead of <code>get_template_directory()</code>. But the function requires "<strong>$path</strong> The full file path to the directory containing translation files".</p>\n<p>All you need is placed here: <a href=\"https://developer.wordpress.org/block-editor/developers/internationalization/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/internationalization/</a>.</p>\n"
},
{
"answer_id": 377275,
"author": "kanlukasz",
"author_id": 133615,
"author_profile": "https://wordpress.stackexchange.com/users/133615",
"pm_score": 0,
"selected": false,
"text": "<p>Inside the <code>wp_set_script_translations</code> function, you use <code>plugins_url('languages', __FILE__)</code> which is not the correct path.</p>\n<p>You should use <code>plugin_dir_path(__FILE__) . 'languages/'</code></p>\n"
},
{
"answer_id": 407896,
"author": "bridgetwes",
"author_id": 224274,
"author_profile": "https://wordpress.stackexchange.com/users/224274",
"pm_score": 0,
"selected": false,
"text": "<p>I too could not get @wordpress/i18n to translate strings, despite following the directions on <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/internationalization/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/how-to-guides/internationalization/</a> under "Provide Your Own Translations".</p>\n<p>The following worked for me:</p>\n<ol>\n<li><p>I was translating to Spanish and using just 'es' in my po file, which used the same in the generated json files. I changed that to es_ES.</p>\n</li>\n<li><p>I had multiple components importing @wordpress/i18n and when I ran "wp i18n make-json languages", separate json files were created for each with a hash in the file name. There is one json file for build/index.js - that file contained all translations and is the only one I needed.</p>\n</li>\n<li><p>I changed the json filename of the file referencing build/index.js (in #2 above) to: {Text Domain}-{locale}-{script-name}.json, so mine became localestr-es_ES-scriptname.json.\nIn the above, localestr is my text domain set in my plugin and in my translation strings, ex: __('Back', 'localestr '). scriptname is the name used with wp_enqueue_script('scriptname')</p>\n</li>\n</ol>\n<p>Many people, in many places say\nwp_set_script_translations( 'myguten-script', 'myguten', plugin_dir_path( <strong>FILE</strong> ) . 'languages' );\nNeeds forward slashes before and/or after languages. I found a forward slash around 'languages' are not needed at all.</p>\n<p>I was also able to leave "domain":"messages" in my json file. That works for me, and I did not need to change "messages" in 3 places to my Text Domain.</p>\n<p>I hope this helps someone else. It's super frustrating to debug because there is so little documentation, debug options, and the documentation is missing a very important bit about the generated json files with wp-cli are not named correctly to automatically get set up with wp_set_script_translations.</p>\n"
}
] | 2019/12/31 | [
"https://wordpress.stackexchange.com/questions/355472",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47357/"
] | I am struggling to load translation in JavaScript for my simple plugin. Translation works for PHP, but not in JS. What seems to be the problem, how can I debug this?
1. I have loaded text domain in my plugin method and this works ok. My text domain is `instantsearch`, locale for my language is `hr`
```
load_plugin_textdomain('instantsearch', FALSE, basename( dirname( __FILE__ ) ) . '/languages/'); // returns true
var_dump(__('No results', 'instantsearch')); // This shows correct translation for my language
```
2. I have generated .json file with WP CLI
```
wp i18n make-json languages/
```
3. This gives me new file `/myplugin/languages/instantsearch-hr-hash.json`. My JS file is `assets/instant-search.js` and somewhere I have read that I need to manually rename that hash. I just copied that file two times and renamed them to the following just to try it out, so something out of those 3 should be working :)
```
instantsearch-hr-47626afcca1bc179bc9eedb6abdc01ff.json
instantsearch-hr-instant-search.json
instantsearch-hr-instantsearch.json
```
4. I have registered the script for translation
```
wp_register_script('instant-search', plugins_url('assets/instant-search.js', __FILE__), array('jquery', 'wp-i18n'), false, true);
wp_enqueue_script('instant-search');
wp_set_script_translations('instant-search', 'instantsearch', plugins_url('languages', __FILE__));
```
5. In the script at the very top I have tried this, but it doesn't give me translation like in PHP, it just shows english default string
```
console.log(wp.i18n.__('No results', 'instantsearch'));
```
6. Here is example of json
```
{"translation-revision-date":"2019-12-31 13:41+0100","generator":"WP-CLI\/2.4.0","source":"assets\/instant-search.js","domain":"messages","locale_data":{"messages":{"":{"domain":"messages","lang":"hr","plural-forms":"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);"},"No results":["Nema prona\u0111enih rezultata"]}}}
```
7. I know I can use `wp_localize_script()` to move string from PHP to JS but from WP 5.\* we should be able to do it | I was having the same problem and this is how I solved it:
First, the generated JSON file has some errors. You need to update where it says `messages` with your text domain. There are three places where that needs to be changed. I also had to change the `lang` attribute to be all lowercase with a dash. Here are the fields I changed:
```
{
"domain": "my-text-domain",
"locale_data": {
"my-text-domain": { // Instead of "messages"
"": {
"domain": "my-text-domain",
"lang": "es-es"
},
...
}
}
}
```
Second, the file name with the md5 hash tends to have the wrong md5 hash, so it's best to rename the file to `{domain}-{locale}-{script-name}.json`, so mine became `my-text-domain-es_ES-my-script-name.js`.
Third, the `wp_set_script_translations` function needs to be called with the right path, and attached to the right hook. This is what I had to do, since I was localizing an admin-side script:
```php
function enqueue_scripts() {
wp_set_script_translations( 'script-name', 'my-text-domain', plugin_dir_path( dirname(__FILE__) ) . 'languages' );
}
add_action( 'admin_enqueue_scripts', 'enqueue_scripts' );
```
Try echoing out the value of `plugin_dir_path( dirname(__FILE__) ) . 'languages'` to make sure you're getting the path where your translation files are.
Once I sorted out all of these little details, my translations started working, so I hope this helps someone else! |
355,476 | <p>I do not find the solution which must surely be surely simple. (I'm new to WP)
I have an ACF field named "partners_order".
I would like to sort it in ascending order (ASC)</p>
<p>here's what i tried</p>
<pre><code><?php $terms = get_terms('type_partenaires');
usort($terms, function($a, $b) {
return get_field('ordre_affichage', $a) - get_field('ordre_affichage', $b);
});
foreach ( $terms as $term ): ?>
<?php echo $term->name; ?>
<?php $loop = new WP_Query( array(
'post_type' => 'partenaires',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'type_partenaires',
'field' => 'ID',
'terms' => $term->term_id,
'orderby' => 'partners_order',
'order' => 'ASC',
),
),
) ); ?>
</code></pre>
<p>if someone could give me a lead to move forward ... thank you</p>
| [
{
"answer_id": 365613,
"author": "Josiah Sprague",
"author_id": 21290,
"author_profile": "https://wordpress.stackexchange.com/users/21290",
"pm_score": 2,
"selected": false,
"text": "<p>I was having the same problem and this is how I solved it:</p>\n\n<p>First, the generated JSON file has some errors. You need to update where it says <code>messages</code> with your text domain. There are three places where that needs to be changed. I also had to change the <code>lang</code> attribute to be all lowercase with a dash. Here are the fields I changed:</p>\n\n<pre><code>{\n \"domain\": \"my-text-domain\",\n \"locale_data\": {\n \"my-text-domain\": { // Instead of \"messages\"\n \"\": {\n \"domain\": \"my-text-domain\",\n \"lang\": \"es-es\"\n },\n ...\n }\n }\n}\n\n</code></pre>\n\n<p>Second, the file name with the md5 hash tends to have the wrong md5 hash, so it's best to rename the file to <code>{domain}-{locale}-{script-name}.json</code>, so mine became <code>my-text-domain-es_ES-my-script-name.js</code>.</p>\n\n<p>Third, the <code>wp_set_script_translations</code> function needs to be called with the right path, and attached to the right hook. This is what I had to do, since I was localizing an admin-side script:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function enqueue_scripts() {\n wp_set_script_translations( 'script-name', 'my-text-domain', plugin_dir_path( dirname(__FILE__) ) . 'languages' );\n}\nadd_action( 'admin_enqueue_scripts', 'enqueue_scripts' );\n</code></pre>\n\n<p>Try echoing out the value of <code>plugin_dir_path( dirname(__FILE__) ) . 'languages'</code> to make sure you're getting the path where your translation files are.</p>\n\n<p>Once I sorted out all of these little details, my translations started working, so I hope this helps someone else!</p>\n"
},
{
"answer_id": 372478,
"author": "Kostiantyn Petlia",
"author_id": 104932,
"author_profile": "https://wordpress.stackexchange.com/users/104932",
"pm_score": 0,
"selected": false,
"text": "<p>I'll leave it here. Perhaps it will help someone. I had the same issue. I did all steps and all looked working, but in JS <code>__('Hello world', 'textdomain');</code> didn't work.</p>\n<p>There are a lot of recommendations about the JSON file for example to use 'nl' instead 'nl_NL', etc. For today (2020.08.06) you shouldn't change a json-file in any way except its name as <code>custom_dir/{domain}-{locale}-{handle}.json</code>.</p>\n<p>The base steps:</p>\n<ol>\n<li>PHP code:</li>\n</ol>\n<pre><code>load_theme_textdomain( 'textdomain', get_template_directory() . '/languages' );\n// ...\nwp_enqueue_script( 'scripts', asset_url( 'js/app.js' ), [ 'jquery', 'wp-i18n' ], null, true );\nwp_set_script_translations( 'scripts', 'textdomain', get_template_directory() .'/languages/js' );\n</code></pre>\n<ol start=\"2\">\n<li><p>I use the Poedit application for creating & translating the <code>nl_NL.po</code> file.</p>\n</li>\n<li><p>With WP-CLI I generate <code>wp i18n make-json ./languages ./languages/js --no-purge --pretty-print</code> a json-file and I reneme it to <code>./languages/js/textdomain-nl_NL-scripts.json</code>.</p>\n</li>\n</ol>\n<p><strong>The essential thing:</strong>\nThe author's mistake is <code>plugins_url('languages', __FILE__)</code> in <code>wp_set_script_translations();</code>. My mistake was a simple <code>get_template_directory_uri()</code> instead of <code>get_template_directory()</code>. But the function requires "<strong>$path</strong> The full file path to the directory containing translation files".</p>\n<p>All you need is placed here: <a href=\"https://developer.wordpress.org/block-editor/developers/internationalization/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/internationalization/</a>.</p>\n"
},
{
"answer_id": 377275,
"author": "kanlukasz",
"author_id": 133615,
"author_profile": "https://wordpress.stackexchange.com/users/133615",
"pm_score": 0,
"selected": false,
"text": "<p>Inside the <code>wp_set_script_translations</code> function, you use <code>plugins_url('languages', __FILE__)</code> which is not the correct path.</p>\n<p>You should use <code>plugin_dir_path(__FILE__) . 'languages/'</code></p>\n"
},
{
"answer_id": 407896,
"author": "bridgetwes",
"author_id": 224274,
"author_profile": "https://wordpress.stackexchange.com/users/224274",
"pm_score": 0,
"selected": false,
"text": "<p>I too could not get @wordpress/i18n to translate strings, despite following the directions on <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/internationalization/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/how-to-guides/internationalization/</a> under "Provide Your Own Translations".</p>\n<p>The following worked for me:</p>\n<ol>\n<li><p>I was translating to Spanish and using just 'es' in my po file, which used the same in the generated json files. I changed that to es_ES.</p>\n</li>\n<li><p>I had multiple components importing @wordpress/i18n and when I ran "wp i18n make-json languages", separate json files were created for each with a hash in the file name. There is one json file for build/index.js - that file contained all translations and is the only one I needed.</p>\n</li>\n<li><p>I changed the json filename of the file referencing build/index.js (in #2 above) to: {Text Domain}-{locale}-{script-name}.json, so mine became localestr-es_ES-scriptname.json.\nIn the above, localestr is my text domain set in my plugin and in my translation strings, ex: __('Back', 'localestr '). scriptname is the name used with wp_enqueue_script('scriptname')</p>\n</li>\n</ol>\n<p>Many people, in many places say\nwp_set_script_translations( 'myguten-script', 'myguten', plugin_dir_path( <strong>FILE</strong> ) . 'languages' );\nNeeds forward slashes before and/or after languages. I found a forward slash around 'languages' are not needed at all.</p>\n<p>I was also able to leave "domain":"messages" in my json file. That works for me, and I did not need to change "messages" in 3 places to my Text Domain.</p>\n<p>I hope this helps someone else. It's super frustrating to debug because there is so little documentation, debug options, and the documentation is missing a very important bit about the generated json files with wp-cli are not named correctly to automatically get set up with wp_set_script_translations.</p>\n"
}
] | 2019/12/31 | [
"https://wordpress.stackexchange.com/questions/355476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180415/"
] | I do not find the solution which must surely be surely simple. (I'm new to WP)
I have an ACF field named "partners\_order".
I would like to sort it in ascending order (ASC)
here's what i tried
```
<?php $terms = get_terms('type_partenaires');
usort($terms, function($a, $b) {
return get_field('ordre_affichage', $a) - get_field('ordre_affichage', $b);
});
foreach ( $terms as $term ): ?>
<?php echo $term->name; ?>
<?php $loop = new WP_Query( array(
'post_type' => 'partenaires',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'type_partenaires',
'field' => 'ID',
'terms' => $term->term_id,
'orderby' => 'partners_order',
'order' => 'ASC',
),
),
) ); ?>
```
if someone could give me a lead to move forward ... thank you | I was having the same problem and this is how I solved it:
First, the generated JSON file has some errors. You need to update where it says `messages` with your text domain. There are three places where that needs to be changed. I also had to change the `lang` attribute to be all lowercase with a dash. Here are the fields I changed:
```
{
"domain": "my-text-domain",
"locale_data": {
"my-text-domain": { // Instead of "messages"
"": {
"domain": "my-text-domain",
"lang": "es-es"
},
...
}
}
}
```
Second, the file name with the md5 hash tends to have the wrong md5 hash, so it's best to rename the file to `{domain}-{locale}-{script-name}.json`, so mine became `my-text-domain-es_ES-my-script-name.js`.
Third, the `wp_set_script_translations` function needs to be called with the right path, and attached to the right hook. This is what I had to do, since I was localizing an admin-side script:
```php
function enqueue_scripts() {
wp_set_script_translations( 'script-name', 'my-text-domain', plugin_dir_path( dirname(__FILE__) ) . 'languages' );
}
add_action( 'admin_enqueue_scripts', 'enqueue_scripts' );
```
Try echoing out the value of `plugin_dir_path( dirname(__FILE__) ) . 'languages'` to make sure you're getting the path where your translation files are.
Once I sorted out all of these little details, my translations started working, so I hope this helps someone else! |
355,478 | <p>I am currently trying to get the current username to add it to the url.
The user should be able to navigate to his own dashboard wich is located under domain.com/username. Is there a way to retrieve the username and add it as variable to the url? </p>
<p>Thank you!</p>
| [
{
"answer_id": 365613,
"author": "Josiah Sprague",
"author_id": 21290,
"author_profile": "https://wordpress.stackexchange.com/users/21290",
"pm_score": 2,
"selected": false,
"text": "<p>I was having the same problem and this is how I solved it:</p>\n\n<p>First, the generated JSON file has some errors. You need to update where it says <code>messages</code> with your text domain. There are three places where that needs to be changed. I also had to change the <code>lang</code> attribute to be all lowercase with a dash. Here are the fields I changed:</p>\n\n<pre><code>{\n \"domain\": \"my-text-domain\",\n \"locale_data\": {\n \"my-text-domain\": { // Instead of \"messages\"\n \"\": {\n \"domain\": \"my-text-domain\",\n \"lang\": \"es-es\"\n },\n ...\n }\n }\n}\n\n</code></pre>\n\n<p>Second, the file name with the md5 hash tends to have the wrong md5 hash, so it's best to rename the file to <code>{domain}-{locale}-{script-name}.json</code>, so mine became <code>my-text-domain-es_ES-my-script-name.js</code>.</p>\n\n<p>Third, the <code>wp_set_script_translations</code> function needs to be called with the right path, and attached to the right hook. This is what I had to do, since I was localizing an admin-side script:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function enqueue_scripts() {\n wp_set_script_translations( 'script-name', 'my-text-domain', plugin_dir_path( dirname(__FILE__) ) . 'languages' );\n}\nadd_action( 'admin_enqueue_scripts', 'enqueue_scripts' );\n</code></pre>\n\n<p>Try echoing out the value of <code>plugin_dir_path( dirname(__FILE__) ) . 'languages'</code> to make sure you're getting the path where your translation files are.</p>\n\n<p>Once I sorted out all of these little details, my translations started working, so I hope this helps someone else!</p>\n"
},
{
"answer_id": 372478,
"author": "Kostiantyn Petlia",
"author_id": 104932,
"author_profile": "https://wordpress.stackexchange.com/users/104932",
"pm_score": 0,
"selected": false,
"text": "<p>I'll leave it here. Perhaps it will help someone. I had the same issue. I did all steps and all looked working, but in JS <code>__('Hello world', 'textdomain');</code> didn't work.</p>\n<p>There are a lot of recommendations about the JSON file for example to use 'nl' instead 'nl_NL', etc. For today (2020.08.06) you shouldn't change a json-file in any way except its name as <code>custom_dir/{domain}-{locale}-{handle}.json</code>.</p>\n<p>The base steps:</p>\n<ol>\n<li>PHP code:</li>\n</ol>\n<pre><code>load_theme_textdomain( 'textdomain', get_template_directory() . '/languages' );\n// ...\nwp_enqueue_script( 'scripts', asset_url( 'js/app.js' ), [ 'jquery', 'wp-i18n' ], null, true );\nwp_set_script_translations( 'scripts', 'textdomain', get_template_directory() .'/languages/js' );\n</code></pre>\n<ol start=\"2\">\n<li><p>I use the Poedit application for creating & translating the <code>nl_NL.po</code> file.</p>\n</li>\n<li><p>With WP-CLI I generate <code>wp i18n make-json ./languages ./languages/js --no-purge --pretty-print</code> a json-file and I reneme it to <code>./languages/js/textdomain-nl_NL-scripts.json</code>.</p>\n</li>\n</ol>\n<p><strong>The essential thing:</strong>\nThe author's mistake is <code>plugins_url('languages', __FILE__)</code> in <code>wp_set_script_translations();</code>. My mistake was a simple <code>get_template_directory_uri()</code> instead of <code>get_template_directory()</code>. But the function requires "<strong>$path</strong> The full file path to the directory containing translation files".</p>\n<p>All you need is placed here: <a href=\"https://developer.wordpress.org/block-editor/developers/internationalization/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/internationalization/</a>.</p>\n"
},
{
"answer_id": 377275,
"author": "kanlukasz",
"author_id": 133615,
"author_profile": "https://wordpress.stackexchange.com/users/133615",
"pm_score": 0,
"selected": false,
"text": "<p>Inside the <code>wp_set_script_translations</code> function, you use <code>plugins_url('languages', __FILE__)</code> which is not the correct path.</p>\n<p>You should use <code>plugin_dir_path(__FILE__) . 'languages/'</code></p>\n"
},
{
"answer_id": 407896,
"author": "bridgetwes",
"author_id": 224274,
"author_profile": "https://wordpress.stackexchange.com/users/224274",
"pm_score": 0,
"selected": false,
"text": "<p>I too could not get @wordpress/i18n to translate strings, despite following the directions on <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/internationalization/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/how-to-guides/internationalization/</a> under "Provide Your Own Translations".</p>\n<p>The following worked for me:</p>\n<ol>\n<li><p>I was translating to Spanish and using just 'es' in my po file, which used the same in the generated json files. I changed that to es_ES.</p>\n</li>\n<li><p>I had multiple components importing @wordpress/i18n and when I ran "wp i18n make-json languages", separate json files were created for each with a hash in the file name. There is one json file for build/index.js - that file contained all translations and is the only one I needed.</p>\n</li>\n<li><p>I changed the json filename of the file referencing build/index.js (in #2 above) to: {Text Domain}-{locale}-{script-name}.json, so mine became localestr-es_ES-scriptname.json.\nIn the above, localestr is my text domain set in my plugin and in my translation strings, ex: __('Back', 'localestr '). scriptname is the name used with wp_enqueue_script('scriptname')</p>\n</li>\n</ol>\n<p>Many people, in many places say\nwp_set_script_translations( 'myguten-script', 'myguten', plugin_dir_path( <strong>FILE</strong> ) . 'languages' );\nNeeds forward slashes before and/or after languages. I found a forward slash around 'languages' are not needed at all.</p>\n<p>I was also able to leave "domain":"messages" in my json file. That works for me, and I did not need to change "messages" in 3 places to my Text Domain.</p>\n<p>I hope this helps someone else. It's super frustrating to debug because there is so little documentation, debug options, and the documentation is missing a very important bit about the generated json files with wp-cli are not named correctly to automatically get set up with wp_set_script_translations.</p>\n"
}
] | 2019/12/31 | [
"https://wordpress.stackexchange.com/questions/355478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180416/"
] | I am currently trying to get the current username to add it to the url.
The user should be able to navigate to his own dashboard wich is located under domain.com/username. Is there a way to retrieve the username and add it as variable to the url?
Thank you! | I was having the same problem and this is how I solved it:
First, the generated JSON file has some errors. You need to update where it says `messages` with your text domain. There are three places where that needs to be changed. I also had to change the `lang` attribute to be all lowercase with a dash. Here are the fields I changed:
```
{
"domain": "my-text-domain",
"locale_data": {
"my-text-domain": { // Instead of "messages"
"": {
"domain": "my-text-domain",
"lang": "es-es"
},
...
}
}
}
```
Second, the file name with the md5 hash tends to have the wrong md5 hash, so it's best to rename the file to `{domain}-{locale}-{script-name}.json`, so mine became `my-text-domain-es_ES-my-script-name.js`.
Third, the `wp_set_script_translations` function needs to be called with the right path, and attached to the right hook. This is what I had to do, since I was localizing an admin-side script:
```php
function enqueue_scripts() {
wp_set_script_translations( 'script-name', 'my-text-domain', plugin_dir_path( dirname(__FILE__) ) . 'languages' );
}
add_action( 'admin_enqueue_scripts', 'enqueue_scripts' );
```
Try echoing out the value of `plugin_dir_path( dirname(__FILE__) ) . 'languages'` to make sure you're getting the path where your translation files are.
Once I sorted out all of these little details, my translations started working, so I hope this helps someone else! |
355,497 | <p>I developed a customer metabox plugin to save user details to db and retrieve them back to Contact Us Page in my website.</p>
<p>But I searched a way to retrieve the data to contact us page and I couldn't find a way. </p>
<p>Please look into this code and kindly tell me a way to retrieve the data updated through <code>metabox.php</code> to <code>page-contact.php</code></p>
<p><strong>metabox.php</strong></p>
<pre><code><?php
add_action('add_meta_boxes', 'wpl_owt_register_metabox_cpt');
function wpl_owt_register_metabox_cpt()
{
global $post;
if(!empty($post))
{
$pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);
if($pageTemplate == 'page-contact.php' )
{
add_meta_box(
'owt-cpt-id', // $id
'Contact Details', // $title
'wpl_owt_book_function', // $callback
'page', // $page
'normal', // $context
'high'); // $priority
}
}
}
/**********Callback function for metabox at custom post type book******************/
function wpl_owt_book_function( $post ) {
//echo "<p>Custom metabox for custom post type</p>";
define("_FILE_", "_FILE_");
wp_nonce_field( basename(_FILE_), "wp_owt_cpt_nonce");
echo "<label for='txtPhoneNum'>Phone</label><br>";
$phone_num = get_post_meta($post->ID, "telNo" , true);
echo "<input type ='tel' name = 'txtPhoneNum' value = '" . $phone_num . "'' placeholder = 'Phone Number' /><br><br>";
echo "<label for='txtEmail'>Email</label><br>";
$email = get_post_meta($post->ID, "email" , true);
echo "<input type ='email' name = 'txtEmail' value = '" . $email . "'' placeholder = 'Email Address' /><br><br>";
echo "<label for='txtHours'>Hours of Operation</label><br>";
$hours = get_post_meta($post->ID, "hourofOps" , true);
echo "<input type ='text' name = 'txtHours' value = '" . $hours . "'' placeholder = 'Working Hours' /><br><br>";
}
add_action("save_post" , "wpl_owt_save_metabox_data" , 10 , 2);
function wpl_owt_save_metabox_data($post_id, $post){
//verify nonce
if(!isset($_POST['wp_owt_cpt_nonce']) || !wp_verify_nonce($_POST['wp_owt_cpt_nonce'], basename(_FILE_))){
return $post_id;
}
//verify slug value
$post_slug = "page";
if($post_slug != $post->post_type){
return;
}
//save value to db filed
$pub_tel = '';
if(isset($_POST['txtPhoneNum'])){
$pub_tel = sanitize_text_field($_POST['txtPhoneNum']);
}
else{
$pub_tel = '';
}
update_post_meta($post_id, "telNo", $pub_tel);
$pub_email = '';
if(isset($_POST['txtEmail'])){
$pub_email = sanitize_text_field($_POST['txtEmail']);
}
else{
$pub_email = '';
}
update_post_meta($post_id, "email", $pub_email);
$pub_hours = '';
if(isset($_POST['txtHours'])){
$pub_hours = sanitize_text_field($_POST['txtHours']);
}
update_post_meta($post_id, "hourofOps", $pub_hours);
}
?>
</code></pre>
<p><strong>page-contact.php</strong></p>
<pre><code> <!-- Contact Info -->
<div class="contact-info col-md-4 col-sm-4 margin-top-20 padding-left-20">
<label class="contact-label pull-left width-wide">Contact Info</label>
<p><strong>IT'S SHOWTIME TOWING</strong><br /><br /> Phone: <a href="tel:0450749863">0450749863</a><br /><br />
Email: <a href="mailto:[email protected]">[email protected]</a><br /><br />
<strong>Hours of Operation</strong><br /><br />
<a href="#">24/7</a><br /><br /> <strong>Terms And Conditions</strong> <a href="terms_conditions.html">Click Here</a></p>
</div>
<!-- // Contact Info -->
</code></pre>
<p>Thank You!</p>
| [
{
"answer_id": 365613,
"author": "Josiah Sprague",
"author_id": 21290,
"author_profile": "https://wordpress.stackexchange.com/users/21290",
"pm_score": 2,
"selected": false,
"text": "<p>I was having the same problem and this is how I solved it:</p>\n\n<p>First, the generated JSON file has some errors. You need to update where it says <code>messages</code> with your text domain. There are three places where that needs to be changed. I also had to change the <code>lang</code> attribute to be all lowercase with a dash. Here are the fields I changed:</p>\n\n<pre><code>{\n \"domain\": \"my-text-domain\",\n \"locale_data\": {\n \"my-text-domain\": { // Instead of \"messages\"\n \"\": {\n \"domain\": \"my-text-domain\",\n \"lang\": \"es-es\"\n },\n ...\n }\n }\n}\n\n</code></pre>\n\n<p>Second, the file name with the md5 hash tends to have the wrong md5 hash, so it's best to rename the file to <code>{domain}-{locale}-{script-name}.json</code>, so mine became <code>my-text-domain-es_ES-my-script-name.js</code>.</p>\n\n<p>Third, the <code>wp_set_script_translations</code> function needs to be called with the right path, and attached to the right hook. This is what I had to do, since I was localizing an admin-side script:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function enqueue_scripts() {\n wp_set_script_translations( 'script-name', 'my-text-domain', plugin_dir_path( dirname(__FILE__) ) . 'languages' );\n}\nadd_action( 'admin_enqueue_scripts', 'enqueue_scripts' );\n</code></pre>\n\n<p>Try echoing out the value of <code>plugin_dir_path( dirname(__FILE__) ) . 'languages'</code> to make sure you're getting the path where your translation files are.</p>\n\n<p>Once I sorted out all of these little details, my translations started working, so I hope this helps someone else!</p>\n"
},
{
"answer_id": 372478,
"author": "Kostiantyn Petlia",
"author_id": 104932,
"author_profile": "https://wordpress.stackexchange.com/users/104932",
"pm_score": 0,
"selected": false,
"text": "<p>I'll leave it here. Perhaps it will help someone. I had the same issue. I did all steps and all looked working, but in JS <code>__('Hello world', 'textdomain');</code> didn't work.</p>\n<p>There are a lot of recommendations about the JSON file for example to use 'nl' instead 'nl_NL', etc. For today (2020.08.06) you shouldn't change a json-file in any way except its name as <code>custom_dir/{domain}-{locale}-{handle}.json</code>.</p>\n<p>The base steps:</p>\n<ol>\n<li>PHP code:</li>\n</ol>\n<pre><code>load_theme_textdomain( 'textdomain', get_template_directory() . '/languages' );\n// ...\nwp_enqueue_script( 'scripts', asset_url( 'js/app.js' ), [ 'jquery', 'wp-i18n' ], null, true );\nwp_set_script_translations( 'scripts', 'textdomain', get_template_directory() .'/languages/js' );\n</code></pre>\n<ol start=\"2\">\n<li><p>I use the Poedit application for creating & translating the <code>nl_NL.po</code> file.</p>\n</li>\n<li><p>With WP-CLI I generate <code>wp i18n make-json ./languages ./languages/js --no-purge --pretty-print</code> a json-file and I reneme it to <code>./languages/js/textdomain-nl_NL-scripts.json</code>.</p>\n</li>\n</ol>\n<p><strong>The essential thing:</strong>\nThe author's mistake is <code>plugins_url('languages', __FILE__)</code> in <code>wp_set_script_translations();</code>. My mistake was a simple <code>get_template_directory_uri()</code> instead of <code>get_template_directory()</code>. But the function requires "<strong>$path</strong> The full file path to the directory containing translation files".</p>\n<p>All you need is placed here: <a href=\"https://developer.wordpress.org/block-editor/developers/internationalization/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/developers/internationalization/</a>.</p>\n"
},
{
"answer_id": 377275,
"author": "kanlukasz",
"author_id": 133615,
"author_profile": "https://wordpress.stackexchange.com/users/133615",
"pm_score": 0,
"selected": false,
"text": "<p>Inside the <code>wp_set_script_translations</code> function, you use <code>plugins_url('languages', __FILE__)</code> which is not the correct path.</p>\n<p>You should use <code>plugin_dir_path(__FILE__) . 'languages/'</code></p>\n"
},
{
"answer_id": 407896,
"author": "bridgetwes",
"author_id": 224274,
"author_profile": "https://wordpress.stackexchange.com/users/224274",
"pm_score": 0,
"selected": false,
"text": "<p>I too could not get @wordpress/i18n to translate strings, despite following the directions on <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/internationalization/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/how-to-guides/internationalization/</a> under "Provide Your Own Translations".</p>\n<p>The following worked for me:</p>\n<ol>\n<li><p>I was translating to Spanish and using just 'es' in my po file, which used the same in the generated json files. I changed that to es_ES.</p>\n</li>\n<li><p>I had multiple components importing @wordpress/i18n and when I ran "wp i18n make-json languages", separate json files were created for each with a hash in the file name. There is one json file for build/index.js - that file contained all translations and is the only one I needed.</p>\n</li>\n<li><p>I changed the json filename of the file referencing build/index.js (in #2 above) to: {Text Domain}-{locale}-{script-name}.json, so mine became localestr-es_ES-scriptname.json.\nIn the above, localestr is my text domain set in my plugin and in my translation strings, ex: __('Back', 'localestr '). scriptname is the name used with wp_enqueue_script('scriptname')</p>\n</li>\n</ol>\n<p>Many people, in many places say\nwp_set_script_translations( 'myguten-script', 'myguten', plugin_dir_path( <strong>FILE</strong> ) . 'languages' );\nNeeds forward slashes before and/or after languages. I found a forward slash around 'languages' are not needed at all.</p>\n<p>I was also able to leave "domain":"messages" in my json file. That works for me, and I did not need to change "messages" in 3 places to my Text Domain.</p>\n<p>I hope this helps someone else. It's super frustrating to debug because there is so little documentation, debug options, and the documentation is missing a very important bit about the generated json files with wp-cli are not named correctly to automatically get set up with wp_set_script_translations.</p>\n"
}
] | 2020/01/01 | [
"https://wordpress.stackexchange.com/questions/355497",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180272/"
] | I developed a customer metabox plugin to save user details to db and retrieve them back to Contact Us Page in my website.
But I searched a way to retrieve the data to contact us page and I couldn't find a way.
Please look into this code and kindly tell me a way to retrieve the data updated through `metabox.php` to `page-contact.php`
**metabox.php**
```
<?php
add_action('add_meta_boxes', 'wpl_owt_register_metabox_cpt');
function wpl_owt_register_metabox_cpt()
{
global $post;
if(!empty($post))
{
$pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);
if($pageTemplate == 'page-contact.php' )
{
add_meta_box(
'owt-cpt-id', // $id
'Contact Details', // $title
'wpl_owt_book_function', // $callback
'page', // $page
'normal', // $context
'high'); // $priority
}
}
}
/**********Callback function for metabox at custom post type book******************/
function wpl_owt_book_function( $post ) {
//echo "<p>Custom metabox for custom post type</p>";
define("_FILE_", "_FILE_");
wp_nonce_field( basename(_FILE_), "wp_owt_cpt_nonce");
echo "<label for='txtPhoneNum'>Phone</label><br>";
$phone_num = get_post_meta($post->ID, "telNo" , true);
echo "<input type ='tel' name = 'txtPhoneNum' value = '" . $phone_num . "'' placeholder = 'Phone Number' /><br><br>";
echo "<label for='txtEmail'>Email</label><br>";
$email = get_post_meta($post->ID, "email" , true);
echo "<input type ='email' name = 'txtEmail' value = '" . $email . "'' placeholder = 'Email Address' /><br><br>";
echo "<label for='txtHours'>Hours of Operation</label><br>";
$hours = get_post_meta($post->ID, "hourofOps" , true);
echo "<input type ='text' name = 'txtHours' value = '" . $hours . "'' placeholder = 'Working Hours' /><br><br>";
}
add_action("save_post" , "wpl_owt_save_metabox_data" , 10 , 2);
function wpl_owt_save_metabox_data($post_id, $post){
//verify nonce
if(!isset($_POST['wp_owt_cpt_nonce']) || !wp_verify_nonce($_POST['wp_owt_cpt_nonce'], basename(_FILE_))){
return $post_id;
}
//verify slug value
$post_slug = "page";
if($post_slug != $post->post_type){
return;
}
//save value to db filed
$pub_tel = '';
if(isset($_POST['txtPhoneNum'])){
$pub_tel = sanitize_text_field($_POST['txtPhoneNum']);
}
else{
$pub_tel = '';
}
update_post_meta($post_id, "telNo", $pub_tel);
$pub_email = '';
if(isset($_POST['txtEmail'])){
$pub_email = sanitize_text_field($_POST['txtEmail']);
}
else{
$pub_email = '';
}
update_post_meta($post_id, "email", $pub_email);
$pub_hours = '';
if(isset($_POST['txtHours'])){
$pub_hours = sanitize_text_field($_POST['txtHours']);
}
update_post_meta($post_id, "hourofOps", $pub_hours);
}
?>
```
**page-contact.php**
```
<!-- Contact Info -->
<div class="contact-info col-md-4 col-sm-4 margin-top-20 padding-left-20">
<label class="contact-label pull-left width-wide">Contact Info</label>
<p><strong>IT'S SHOWTIME TOWING</strong><br /><br /> Phone: <a href="tel:0450749863">0450749863</a><br /><br />
Email: <a href="mailto:[email protected]">[email protected]</a><br /><br />
<strong>Hours of Operation</strong><br /><br />
<a href="#">24/7</a><br /><br /> <strong>Terms And Conditions</strong> <a href="terms_conditions.html">Click Here</a></p>
</div>
<!-- // Contact Info -->
```
Thank You! | I was having the same problem and this is how I solved it:
First, the generated JSON file has some errors. You need to update where it says `messages` with your text domain. There are three places where that needs to be changed. I also had to change the `lang` attribute to be all lowercase with a dash. Here are the fields I changed:
```
{
"domain": "my-text-domain",
"locale_data": {
"my-text-domain": { // Instead of "messages"
"": {
"domain": "my-text-domain",
"lang": "es-es"
},
...
}
}
}
```
Second, the file name with the md5 hash tends to have the wrong md5 hash, so it's best to rename the file to `{domain}-{locale}-{script-name}.json`, so mine became `my-text-domain-es_ES-my-script-name.js`.
Third, the `wp_set_script_translations` function needs to be called with the right path, and attached to the right hook. This is what I had to do, since I was localizing an admin-side script:
```php
function enqueue_scripts() {
wp_set_script_translations( 'script-name', 'my-text-domain', plugin_dir_path( dirname(__FILE__) ) . 'languages' );
}
add_action( 'admin_enqueue_scripts', 'enqueue_scripts' );
```
Try echoing out the value of `plugin_dir_path( dirname(__FILE__) ) . 'languages'` to make sure you're getting the path where your translation files are.
Once I sorted out all of these little details, my translations started working, so I hope this helps someone else! |
355,503 | <p>I'm using W3 Total Cache plugin for my WordPress site.
I've enabled Lazy Load setting option, but I want to disable the option for the specific post type. How can I hook and disable it?</p>
| [
{
"answer_id": 355534,
"author": "Arpit Patel",
"author_id": 180410,
"author_profile": "https://wordpress.stackexchange.com/users/180410",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this filter,</p>\n\n<pre>function ar_lazyload_deactivate() {\n if ( is_singular( 'posttype name' ) ) {\n add_filter( 'do_rocket_lazyload', '__return_false' );\n }\n}\nadd_filter( 'wp', __NAMESPACE__ . '\\ar_lazyload_deactivate' );</pre>\n"
},
{
"answer_id": 396623,
"author": "Constantin",
"author_id": 199046,
"author_profile": "https://wordpress.stackexchange.com/users/199046",
"pm_score": 1,
"selected": false,
"text": "<p>This answer might be a bit too late but here goes: W3 Total Cache will skip lazy loading images that have class "no-lazy". This means that you can hook to the <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\">get_the_post_thumbnail()</a> filter <a href=\"https://developer.wordpress.org/reference/hooks/post_thumbnail_html/\" rel=\"nofollow noreferrer\">post_thumbnail_html</a> and add the class to the image.</p>\n<p>Here's an example:</p>\n<pre><code>/**\n * Disable W3 Total Cache lazy load for post type "post"\n *\n * @param string $html\n * @param int $post_id\n * @param int $image_id\n * @param string|int[] $size\n * @param string|array $attr\n */\nfunction _post_thumbnail_html( $html, $post_id, $image_id, $size, $attr ){\n\n if( !empty( $html ) ){\n $post = get_post( $post_id );\n\n if( 'post' === $post->post_type ){\n if( isset( $attr['class'] ) ){\n $attr['class'] .= ' no-lazy';\n }else{\n if( !is_array( $attr ) ){\n $attr = array();\n }\n\n $attr['class'] = 'no-lazy';\n }\n\n $html = wp_get_attachment_image( $image_id, $size, false, $attr );\n }\n\n }\n\n return $html;\n}\nadd_filter( 'post_thumbnail_html', '_post_thumbnail_html', 10, 5 );\n</code></pre>\n"
}
] | 2020/01/01 | [
"https://wordpress.stackexchange.com/questions/355503",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101518/"
] | I'm using W3 Total Cache plugin for my WordPress site.
I've enabled Lazy Load setting option, but I want to disable the option for the specific post type. How can I hook and disable it? | This answer might be a bit too late but here goes: W3 Total Cache will skip lazy loading images that have class "no-lazy". This means that you can hook to the [get\_the\_post\_thumbnail()](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/) filter [post\_thumbnail\_html](https://developer.wordpress.org/reference/hooks/post_thumbnail_html/) and add the class to the image.
Here's an example:
```
/**
* Disable W3 Total Cache lazy load for post type "post"
*
* @param string $html
* @param int $post_id
* @param int $image_id
* @param string|int[] $size
* @param string|array $attr
*/
function _post_thumbnail_html( $html, $post_id, $image_id, $size, $attr ){
if( !empty( $html ) ){
$post = get_post( $post_id );
if( 'post' === $post->post_type ){
if( isset( $attr['class'] ) ){
$attr['class'] .= ' no-lazy';
}else{
if( !is_array( $attr ) ){
$attr = array();
}
$attr['class'] = 'no-lazy';
}
$html = wp_get_attachment_image( $image_id, $size, false, $attr );
}
}
return $html;
}
add_filter( 'post_thumbnail_html', '_post_thumbnail_html', 10, 5 );
``` |
355,553 | <p>I have a bunch of custom fields in my REST API response, and I need to refactor the code for it, so I'm creating an integration test for it, just to make sure nothing breaks in the process of refactoring.</p>
<p>The testing suite was build using <a href="https://developer.wordpress.org/cli/commands/scaffold/plugin-tests/" rel="nofollow noreferrer">wp scaffold for plugin tests</a>. The test looks like:</p>
<pre class="lang-php prettyprint-override"><code><?php
/**
* Class Api_Docs_Page
*
* @package My_Plugin\Routes\Endpoints
*/
namespace My_Plugin\Tests\Routes\Endpoints;
use WP_REST_Request;
use WP_UnitTestCase;
/**
* Class that tests the /wp-json/wp/v2/pages?slug=api-docs response.
*/
class Api_Docs_Page extends WP_UnitTestCase {
private $author_id;
private $api_docs_page_id;
/**
* Test suite setUp method
*/
public function setUp() {
parent::setUp();
// Set up pretty permalinks so that the rest route works with slugs.
$this->set_permalink_structure( '/%postname%/' );
flush_rewrite_rules();
// The way the plugin is set up requires this to exist if we want to create a user using WP factories.
$_REQUEST['_wpnonce_create-user'] = wp_create_nonce( 'create-user' );
$this->author_id = $this->factory->user->create(
[
'user_email' => '[email protected]',
'role' => 'administrator',
]
);
$this->api_docs_page_id = $this->factory->post->create(
[
'post_title' => 'API Docs',
'post_type' => 'page',
]
);
// ACF Field - because I'm still using ACF, don't judge me :p
update_field( 'api_docs_page', $this->api_docs_page_id, 'options' );
// Create the page and all the fields. Will come later on
}
/**
* Test suite tearDown method
*/
public function tearDown() {
parent::tearDown();
}
/**
* Test if the response is correct
*/
public function test_api_docs_page_response() {
// $request = new WP_REST_Request( 'GET', '/wp/v2/pages' );
// $request = new WP_REST_Request( 'GET', '/wp/v2/pages?slug=api-docs' );
$request = new WP_REST_Request( 'GET', "/wp/v2/pages/{$this->api_docs_page_id}" );
$response = rest_get_server()->dispatch( $request );
$page_data = $response->get_data();
error_log( print_r( $page_data, true ) );
}
}
</code></pre>
<p>Now, the <code>$request = new WP_REST_Request( 'GET', '/wp/v2/pages' );</code> works, and I see the data when I run my test, all great.</p>
<p>This <code>$request = new WP_REST_Request( 'GET', "/wp/v2/pages/{$this->api_docs_page_id}" );</code> also works, and I can see the page response I've created with my factory method.</p>
<p>But this</p>
<pre class="lang-php prettyprint-override"><code>$request = new WP_REST_Request( 'GET', '/wp/v2/pages?slug=api-docs' );
</code></pre>
<p>Doesn't work and returns</p>
<pre><code>(
[code] => rest_no_route
[message] => No route was found matching the URL and request method
[data] => Array
(
[status] => 404
)
)
</code></pre>
<p>The real response, when I try it in the postman works with the slug.</p>
<p>I've added the permalink structure in the <code>setUp</code> method but I'm not sure that helped.</p>
<p>Any idea why the <code>slug</code> lookup isn't working in my test?</p>
| [
{
"answer_id": 355534,
"author": "Arpit Patel",
"author_id": 180410,
"author_profile": "https://wordpress.stackexchange.com/users/180410",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this filter,</p>\n\n<pre>function ar_lazyload_deactivate() {\n if ( is_singular( 'posttype name' ) ) {\n add_filter( 'do_rocket_lazyload', '__return_false' );\n }\n}\nadd_filter( 'wp', __NAMESPACE__ . '\\ar_lazyload_deactivate' );</pre>\n"
},
{
"answer_id": 396623,
"author": "Constantin",
"author_id": 199046,
"author_profile": "https://wordpress.stackexchange.com/users/199046",
"pm_score": 1,
"selected": false,
"text": "<p>This answer might be a bit too late but here goes: W3 Total Cache will skip lazy loading images that have class "no-lazy". This means that you can hook to the <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\">get_the_post_thumbnail()</a> filter <a href=\"https://developer.wordpress.org/reference/hooks/post_thumbnail_html/\" rel=\"nofollow noreferrer\">post_thumbnail_html</a> and add the class to the image.</p>\n<p>Here's an example:</p>\n<pre><code>/**\n * Disable W3 Total Cache lazy load for post type "post"\n *\n * @param string $html\n * @param int $post_id\n * @param int $image_id\n * @param string|int[] $size\n * @param string|array $attr\n */\nfunction _post_thumbnail_html( $html, $post_id, $image_id, $size, $attr ){\n\n if( !empty( $html ) ){\n $post = get_post( $post_id );\n\n if( 'post' === $post->post_type ){\n if( isset( $attr['class'] ) ){\n $attr['class'] .= ' no-lazy';\n }else{\n if( !is_array( $attr ) ){\n $attr = array();\n }\n\n $attr['class'] = 'no-lazy';\n }\n\n $html = wp_get_attachment_image( $image_id, $size, false, $attr );\n }\n\n }\n\n return $html;\n}\nadd_filter( 'post_thumbnail_html', '_post_thumbnail_html', 10, 5 );\n</code></pre>\n"
}
] | 2020/01/02 | [
"https://wordpress.stackexchange.com/questions/355553",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58895/"
] | I have a bunch of custom fields in my REST API response, and I need to refactor the code for it, so I'm creating an integration test for it, just to make sure nothing breaks in the process of refactoring.
The testing suite was build using [wp scaffold for plugin tests](https://developer.wordpress.org/cli/commands/scaffold/plugin-tests/). The test looks like:
```php
<?php
/**
* Class Api_Docs_Page
*
* @package My_Plugin\Routes\Endpoints
*/
namespace My_Plugin\Tests\Routes\Endpoints;
use WP_REST_Request;
use WP_UnitTestCase;
/**
* Class that tests the /wp-json/wp/v2/pages?slug=api-docs response.
*/
class Api_Docs_Page extends WP_UnitTestCase {
private $author_id;
private $api_docs_page_id;
/**
* Test suite setUp method
*/
public function setUp() {
parent::setUp();
// Set up pretty permalinks so that the rest route works with slugs.
$this->set_permalink_structure( '/%postname%/' );
flush_rewrite_rules();
// The way the plugin is set up requires this to exist if we want to create a user using WP factories.
$_REQUEST['_wpnonce_create-user'] = wp_create_nonce( 'create-user' );
$this->author_id = $this->factory->user->create(
[
'user_email' => '[email protected]',
'role' => 'administrator',
]
);
$this->api_docs_page_id = $this->factory->post->create(
[
'post_title' => 'API Docs',
'post_type' => 'page',
]
);
// ACF Field - because I'm still using ACF, don't judge me :p
update_field( 'api_docs_page', $this->api_docs_page_id, 'options' );
// Create the page and all the fields. Will come later on
}
/**
* Test suite tearDown method
*/
public function tearDown() {
parent::tearDown();
}
/**
* Test if the response is correct
*/
public function test_api_docs_page_response() {
// $request = new WP_REST_Request( 'GET', '/wp/v2/pages' );
// $request = new WP_REST_Request( 'GET', '/wp/v2/pages?slug=api-docs' );
$request = new WP_REST_Request( 'GET', "/wp/v2/pages/{$this->api_docs_page_id}" );
$response = rest_get_server()->dispatch( $request );
$page_data = $response->get_data();
error_log( print_r( $page_data, true ) );
}
}
```
Now, the `$request = new WP_REST_Request( 'GET', '/wp/v2/pages' );` works, and I see the data when I run my test, all great.
This `$request = new WP_REST_Request( 'GET', "/wp/v2/pages/{$this->api_docs_page_id}" );` also works, and I can see the page response I've created with my factory method.
But this
```php
$request = new WP_REST_Request( 'GET', '/wp/v2/pages?slug=api-docs' );
```
Doesn't work and returns
```
(
[code] => rest_no_route
[message] => No route was found matching the URL and request method
[data] => Array
(
[status] => 404
)
)
```
The real response, when I try it in the postman works with the slug.
I've added the permalink structure in the `setUp` method but I'm not sure that helped.
Any idea why the `slug` lookup isn't working in my test? | This answer might be a bit too late but here goes: W3 Total Cache will skip lazy loading images that have class "no-lazy". This means that you can hook to the [get\_the\_post\_thumbnail()](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/) filter [post\_thumbnail\_html](https://developer.wordpress.org/reference/hooks/post_thumbnail_html/) and add the class to the image.
Here's an example:
```
/**
* Disable W3 Total Cache lazy load for post type "post"
*
* @param string $html
* @param int $post_id
* @param int $image_id
* @param string|int[] $size
* @param string|array $attr
*/
function _post_thumbnail_html( $html, $post_id, $image_id, $size, $attr ){
if( !empty( $html ) ){
$post = get_post( $post_id );
if( 'post' === $post->post_type ){
if( isset( $attr['class'] ) ){
$attr['class'] .= ' no-lazy';
}else{
if( !is_array( $attr ) ){
$attr = array();
}
$attr['class'] = 'no-lazy';
}
$html = wp_get_attachment_image( $image_id, $size, false, $attr );
}
}
return $html;
}
add_filter( 'post_thumbnail_html', '_post_thumbnail_html', 10, 5 );
``` |
355,566 | <p>I'm trying to create a table filled with data from database so basically I have to use php for that reason. however I couldn't find a way to implement my code in custom HTML. most of my php code shows up not executed, it's like I've added php into text format.
here's an image explaining my situation.</p>
<p><a href="https://i.stack.imgur.com/YTIXn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YTIXn.png" alt="enter image description here"></a></p>
<p>.</p>
<p>should I change the theme I'm working with or is it something I don't know?
I'm new to this so please help me.
thanks.</p>
| [
{
"answer_id": 355534,
"author": "Arpit Patel",
"author_id": 180410,
"author_profile": "https://wordpress.stackexchange.com/users/180410",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this filter,</p>\n\n<pre>function ar_lazyload_deactivate() {\n if ( is_singular( 'posttype name' ) ) {\n add_filter( 'do_rocket_lazyload', '__return_false' );\n }\n}\nadd_filter( 'wp', __NAMESPACE__ . '\\ar_lazyload_deactivate' );</pre>\n"
},
{
"answer_id": 396623,
"author": "Constantin",
"author_id": 199046,
"author_profile": "https://wordpress.stackexchange.com/users/199046",
"pm_score": 1,
"selected": false,
"text": "<p>This answer might be a bit too late but here goes: W3 Total Cache will skip lazy loading images that have class "no-lazy". This means that you can hook to the <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\">get_the_post_thumbnail()</a> filter <a href=\"https://developer.wordpress.org/reference/hooks/post_thumbnail_html/\" rel=\"nofollow noreferrer\">post_thumbnail_html</a> and add the class to the image.</p>\n<p>Here's an example:</p>\n<pre><code>/**\n * Disable W3 Total Cache lazy load for post type "post"\n *\n * @param string $html\n * @param int $post_id\n * @param int $image_id\n * @param string|int[] $size\n * @param string|array $attr\n */\nfunction _post_thumbnail_html( $html, $post_id, $image_id, $size, $attr ){\n\n if( !empty( $html ) ){\n $post = get_post( $post_id );\n\n if( 'post' === $post->post_type ){\n if( isset( $attr['class'] ) ){\n $attr['class'] .= ' no-lazy';\n }else{\n if( !is_array( $attr ) ){\n $attr = array();\n }\n\n $attr['class'] = 'no-lazy';\n }\n\n $html = wp_get_attachment_image( $image_id, $size, false, $attr );\n }\n\n }\n\n return $html;\n}\nadd_filter( 'post_thumbnail_html', '_post_thumbnail_html', 10, 5 );\n</code></pre>\n"
}
] | 2020/01/02 | [
"https://wordpress.stackexchange.com/questions/355566",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180367/"
] | I'm trying to create a table filled with data from database so basically I have to use php for that reason. however I couldn't find a way to implement my code in custom HTML. most of my php code shows up not executed, it's like I've added php into text format.
here's an image explaining my situation.
[](https://i.stack.imgur.com/YTIXn.png)
.
should I change the theme I'm working with or is it something I don't know?
I'm new to this so please help me.
thanks. | This answer might be a bit too late but here goes: W3 Total Cache will skip lazy loading images that have class "no-lazy". This means that you can hook to the [get\_the\_post\_thumbnail()](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/) filter [post\_thumbnail\_html](https://developer.wordpress.org/reference/hooks/post_thumbnail_html/) and add the class to the image.
Here's an example:
```
/**
* Disable W3 Total Cache lazy load for post type "post"
*
* @param string $html
* @param int $post_id
* @param int $image_id
* @param string|int[] $size
* @param string|array $attr
*/
function _post_thumbnail_html( $html, $post_id, $image_id, $size, $attr ){
if( !empty( $html ) ){
$post = get_post( $post_id );
if( 'post' === $post->post_type ){
if( isset( $attr['class'] ) ){
$attr['class'] .= ' no-lazy';
}else{
if( !is_array( $attr ) ){
$attr = array();
}
$attr['class'] = 'no-lazy';
}
$html = wp_get_attachment_image( $image_id, $size, false, $attr );
}
}
return $html;
}
add_filter( 'post_thumbnail_html', '_post_thumbnail_html', 10, 5 );
``` |
355,567 | <p>I am trying to create some "cards" to show data from another CPT so I need to store the post ID as part of the block.</p>
<p>The code below has a select in the sidebar which allows you to select the post ID and renders the HTML via a serverSideRender block</p>
<p>and looking at the HTML created and saved and return in the editor reload if has the data (post ID) in the comment block as shown here</p>
<pre><code><!-- wp:mvc/block-mvc-offer-details {"data_offer":"2426"} /-->
</code></pre>
<p>The front-end all works as well and renders the code correctly </p>
<p>But when you reload/re-edit the post the code wipes out the setting and errors the select is not set and no post id is not passed to the server-side code</p>
<p>And the comment gets reset to this without the data ( I can see the correct string in the page source code it gets stripped by JS )</p>
<pre><code><!-- wp:mvc/block-mvc-offer-details /-->
</code></pre>
<p>What have I missed???</p>
<pre><code>/**
* BLOCK: mvc-landing-pages
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
// Import CSS.
import './editor.scss';
import './style.scss';
const {__} = wp.i18n; // Import __() from wp.i18n
const {registerBlockType} = wp.blocks; // Import registerBlockType() from wp.blocks
const {InspectorControls} = wp.blockEditor;
const {Spinner, PanelBody, SelectControl,RangeControl,PanelRow,FormToggle} = wp.components;
const {withSelect} = wp.data;
const {Fragment} = wp.element;
const {serverSideRender: ServerSideRender} = wp;
/**
* Register: a Gutenberg Block.
*
* Registers a new block provided a unique name and an object defining its
* behavior. Once registered, the block is made editor as an option to any
* editor interface where blocks are implemented.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/
* @param {string} name Block name.
* @param {Object} settings Block settings.
* @return {?WPBlock} The block, if it has been successfully
* registered; otherwise `undefined`.
*/
registerBlockType('mvc/block-mvc-offer-details', {
// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __('MVC Offer details - MVC Block'), // Block title.
icon: 'tickets-alt', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
category: 'mvc-blocks', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
keywords: [
__('mvc — CGB Block'),
__('Attractions'),
],
attributes: {
data_offer: {
type: 'number',
},
},
getEditWrapperProps( props ) {
console.log(props);
const { data_offer } = props;
console.log(data_offer);
return {
'data_offer': data_offer,
};
},
/**
* The edit function describes the structure of your block in the context of the editor.
* This represents what the editor will render when the block is used.
*
* The "edit" property must be a valid function.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
*
*
* @returns {Mixed} JSX Component.
*/
edit: withSelect(select => {
return {
offers: select('core').getEntityRecords('postType', 'offer-landing', {per_page: -1})
//, fields: ['id', 'name', 'location']
};
})((props) => {
let {
attributes: {data_offer},
className, setAttributes, offers
} = props;
if ( ! offers) {
return (
<p className={className}>
<Spinner/>
{__('Loading Resorts', 'mvc')}
</p>
);
}
let options = offers.map(obj => {
var options = {};
options = {label: obj.title.rendered, value: obj.id};
return options;
});
options.unshift({label: 'Select Offer', value: null});
return (<Fragment>
<InspectorControls>
<PanelBody title={__('Offer Settings')} >
<PanelRow>
<label
htmlFor="mvc-offers"
>
{ __( 'Resort', 'mvc' ) }
</label>
<SelectControl
id="mvc-offers"
label={__('Offer name', 'mvc')}
value={data_offer}
onChange={data_offer => setAttributes({data_offer})}
options={options}
/>
</PanelRow>
</PanelBody>
</InspectorControls>
<ServerSideRender block="mvc/block-mvc-offer-details"
attributes={{
data_offer: data_offer,
class_name: className,
}}
/>
</Fragment>);
}),
/**
* The save function defines the way in which the different attributes should be combined
* into the final markup, which is then serialized by Gutenberg into post_content.
*
* The "save" property must be specified and must be a valid function.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
*
* @param {Object} props Props.
* @returns {Mixed} JSX Frontend HTML.
*/
save: (props) => {
return null
},});
</code></pre>
| [
{
"answer_id": 355685,
"author": "websevendev",
"author_id": 180566,
"author_profile": "https://wordpress.stackexchange.com/users/180566",
"pm_score": 2,
"selected": true,
"text": "<p>First thing that jumps out is that in:</p>\n\n<p><code><!-- wp:mvc/block-mvc-offer-details {\"data_offer\":\"2426\"} /--></code></p>\n\n<p>the <code>data_offer</code> value is stored as a string while it's defined attribute type is <code>number</code>.</p>\n\n<p>This could be why it's stripped after reload. While <code>select('core').getEntityRecords</code> does return IDs as integers it's possible that after passing that data to <code><SelectControl></code> and then receiving the selected value back by it's <code>onChange(event.target.value)</code> it has lost it's type by being in the DOM.</p>\n\n<p>Try: <code>onChange={data_offer => setAttributes({data_offer: parseInt(data_offer)})}</code></p>\n"
},
{
"answer_id": 355776,
"author": "getdave",
"author_id": 26122,
"author_profile": "https://wordpress.stackexchange.com/users/26122",
"pm_score": 0,
"selected": false,
"text": "<p>You might also like to take a look at <a href=\"https://github.com/WordPress/WordPress/blob/0be749362adbf568ff250c4686320776926d0969/wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php#L63\" rel=\"nofollow noreferrer\">the REST API endpoint that handles block rendering for <code>ServerSideRender</code></a>.</p>\n\n<p>If I understand correctly from your followup post in <a href=\"https://wordpress.slack.com/archives/C02QB2JS7/p1578089674158100\" rel=\"nofollow noreferrer\">WP Slack</a> (<a href=\"https://make.wordpress.org/chat/\" rel=\"nofollow noreferrer\">registration required</a>) you want to pass down a post ID as a block attribute. In that case you need to be sure that you have a matching attribute for \"post ID\" registered for the <code>block-mvc-offer-details</code> block. This is because the REST API endpoint <code>attributes</code> argument <a href=\"https://github.com/WordPress/WordPress/blob/0be749362adbf568ff250c4686320776926d0969/wp-includes/class-wp-block-type.php#L200\" rel=\"nofollow noreferrer\">calls <code>get_attributes()</code> as it expects the attributes to match those registered on the block</a>. </p>\n"
}
] | 2020/01/02 | [
"https://wordpress.stackexchange.com/questions/355567",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/176/"
] | I am trying to create some "cards" to show data from another CPT so I need to store the post ID as part of the block.
The code below has a select in the sidebar which allows you to select the post ID and renders the HTML via a serverSideRender block
and looking at the HTML created and saved and return in the editor reload if has the data (post ID) in the comment block as shown here
```
<!-- wp:mvc/block-mvc-offer-details {"data_offer":"2426"} /-->
```
The front-end all works as well and renders the code correctly
But when you reload/re-edit the post the code wipes out the setting and errors the select is not set and no post id is not passed to the server-side code
And the comment gets reset to this without the data ( I can see the correct string in the page source code it gets stripped by JS )
```
<!-- wp:mvc/block-mvc-offer-details /-->
```
What have I missed???
```
/**
* BLOCK: mvc-landing-pages
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
// Import CSS.
import './editor.scss';
import './style.scss';
const {__} = wp.i18n; // Import __() from wp.i18n
const {registerBlockType} = wp.blocks; // Import registerBlockType() from wp.blocks
const {InspectorControls} = wp.blockEditor;
const {Spinner, PanelBody, SelectControl,RangeControl,PanelRow,FormToggle} = wp.components;
const {withSelect} = wp.data;
const {Fragment} = wp.element;
const {serverSideRender: ServerSideRender} = wp;
/**
* Register: a Gutenberg Block.
*
* Registers a new block provided a unique name and an object defining its
* behavior. Once registered, the block is made editor as an option to any
* editor interface where blocks are implemented.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/
* @param {string} name Block name.
* @param {Object} settings Block settings.
* @return {?WPBlock} The block, if it has been successfully
* registered; otherwise `undefined`.
*/
registerBlockType('mvc/block-mvc-offer-details', {
// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __('MVC Offer details - MVC Block'), // Block title.
icon: 'tickets-alt', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
category: 'mvc-blocks', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
keywords: [
__('mvc — CGB Block'),
__('Attractions'),
],
attributes: {
data_offer: {
type: 'number',
},
},
getEditWrapperProps( props ) {
console.log(props);
const { data_offer } = props;
console.log(data_offer);
return {
'data_offer': data_offer,
};
},
/**
* The edit function describes the structure of your block in the context of the editor.
* This represents what the editor will render when the block is used.
*
* The "edit" property must be a valid function.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
*
*
* @returns {Mixed} JSX Component.
*/
edit: withSelect(select => {
return {
offers: select('core').getEntityRecords('postType', 'offer-landing', {per_page: -1})
//, fields: ['id', 'name', 'location']
};
})((props) => {
let {
attributes: {data_offer},
className, setAttributes, offers
} = props;
if ( ! offers) {
return (
<p className={className}>
<Spinner/>
{__('Loading Resorts', 'mvc')}
</p>
);
}
let options = offers.map(obj => {
var options = {};
options = {label: obj.title.rendered, value: obj.id};
return options;
});
options.unshift({label: 'Select Offer', value: null});
return (<Fragment>
<InspectorControls>
<PanelBody title={__('Offer Settings')} >
<PanelRow>
<label
htmlFor="mvc-offers"
>
{ __( 'Resort', 'mvc' ) }
</label>
<SelectControl
id="mvc-offers"
label={__('Offer name', 'mvc')}
value={data_offer}
onChange={data_offer => setAttributes({data_offer})}
options={options}
/>
</PanelRow>
</PanelBody>
</InspectorControls>
<ServerSideRender block="mvc/block-mvc-offer-details"
attributes={{
data_offer: data_offer,
class_name: className,
}}
/>
</Fragment>);
}),
/**
* The save function defines the way in which the different attributes should be combined
* into the final markup, which is then serialized by Gutenberg into post_content.
*
* The "save" property must be specified and must be a valid function.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
*
* @param {Object} props Props.
* @returns {Mixed} JSX Frontend HTML.
*/
save: (props) => {
return null
},});
``` | First thing that jumps out is that in:
`<!-- wp:mvc/block-mvc-offer-details {"data_offer":"2426"} /-->`
the `data_offer` value is stored as a string while it's defined attribute type is `number`.
This could be why it's stripped after reload. While `select('core').getEntityRecords` does return IDs as integers it's possible that after passing that data to `<SelectControl>` and then receiving the selected value back by it's `onChange(event.target.value)` it has lost it's type by being in the DOM.
Try: `onChange={data_offer => setAttributes({data_offer: parseInt(data_offer)})}` |
355,646 | <p>I place the following code within the WP 'init' callback (or when plugins are loaded).</p>
<pre><code>add_shortcode('my_shortcode',
function($atts, $content ='') { die(); }
);
if (!shortcode_exists('my_shortcode')) die();
</code></pre>
<p>In my page I put "<strong>[my_shortcode]</strong>"</p>
<p>When I view the page I get "****"</p>
<p>Any idea what happened to my code?</p>
<hr>
<p>Update:
I have simplified the problem.</p>
<p>I added the shortcode definition in my theme's index.php file.</p>
<pre><code><?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package GeneratePress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
add_shortcode('myt_active_plugins',
function($atts, $content, $name) {
return 'Shortcode injected';
}
);
</code></pre>
<p>I deactivated all plugins.</p>
<p>I (re)installed WP3.5.2</p>
<p>I created a post:</p>
<pre><code>Welcome *[myt_active_plugins]*
</code></pre>
<p>I published the post and when I viewed it I got:</p>
<pre><code>Welcome **
</code></pre>
<p>As a final check I installed a shortcode plugin, (Shortcodes Ultimate) and it acted the same.</p>
| [
{
"answer_id": 355685,
"author": "websevendev",
"author_id": 180566,
"author_profile": "https://wordpress.stackexchange.com/users/180566",
"pm_score": 2,
"selected": true,
"text": "<p>First thing that jumps out is that in:</p>\n\n<p><code><!-- wp:mvc/block-mvc-offer-details {\"data_offer\":\"2426\"} /--></code></p>\n\n<p>the <code>data_offer</code> value is stored as a string while it's defined attribute type is <code>number</code>.</p>\n\n<p>This could be why it's stripped after reload. While <code>select('core').getEntityRecords</code> does return IDs as integers it's possible that after passing that data to <code><SelectControl></code> and then receiving the selected value back by it's <code>onChange(event.target.value)</code> it has lost it's type by being in the DOM.</p>\n\n<p>Try: <code>onChange={data_offer => setAttributes({data_offer: parseInt(data_offer)})}</code></p>\n"
},
{
"answer_id": 355776,
"author": "getdave",
"author_id": 26122,
"author_profile": "https://wordpress.stackexchange.com/users/26122",
"pm_score": 0,
"selected": false,
"text": "<p>You might also like to take a look at <a href=\"https://github.com/WordPress/WordPress/blob/0be749362adbf568ff250c4686320776926d0969/wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php#L63\" rel=\"nofollow noreferrer\">the REST API endpoint that handles block rendering for <code>ServerSideRender</code></a>.</p>\n\n<p>If I understand correctly from your followup post in <a href=\"https://wordpress.slack.com/archives/C02QB2JS7/p1578089674158100\" rel=\"nofollow noreferrer\">WP Slack</a> (<a href=\"https://make.wordpress.org/chat/\" rel=\"nofollow noreferrer\">registration required</a>) you want to pass down a post ID as a block attribute. In that case you need to be sure that you have a matching attribute for \"post ID\" registered for the <code>block-mvc-offer-details</code> block. This is because the REST API endpoint <code>attributes</code> argument <a href=\"https://github.com/WordPress/WordPress/blob/0be749362adbf568ff250c4686320776926d0969/wp-includes/class-wp-block-type.php#L200\" rel=\"nofollow noreferrer\">calls <code>get_attributes()</code> as it expects the attributes to match those registered on the block</a>. </p>\n"
}
] | 2020/01/03 | [
"https://wordpress.stackexchange.com/questions/355646",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180541/"
] | I place the following code within the WP 'init' callback (or when plugins are loaded).
```
add_shortcode('my_shortcode',
function($atts, $content ='') { die(); }
);
if (!shortcode_exists('my_shortcode')) die();
```
In my page I put "**[my\_shortcode]**"
When I view the page I get "\*\*\*\*"
Any idea what happened to my code?
---
Update:
I have simplified the problem.
I added the shortcode definition in my theme's index.php file.
```
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package GeneratePress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
add_shortcode('myt_active_plugins',
function($atts, $content, $name) {
return 'Shortcode injected';
}
);
```
I deactivated all plugins.
I (re)installed WP3.5.2
I created a post:
```
Welcome *[myt_active_plugins]*
```
I published the post and when I viewed it I got:
```
Welcome **
```
As a final check I installed a shortcode plugin, (Shortcodes Ultimate) and it acted the same. | First thing that jumps out is that in:
`<!-- wp:mvc/block-mvc-offer-details {"data_offer":"2426"} /-->`
the `data_offer` value is stored as a string while it's defined attribute type is `number`.
This could be why it's stripped after reload. While `select('core').getEntityRecords` does return IDs as integers it's possible that after passing that data to `<SelectControl>` and then receiving the selected value back by it's `onChange(event.target.value)` it has lost it's type by being in the DOM.
Try: `onChange={data_offer => setAttributes({data_offer: parseInt(data_offer)})}` |
355,649 | <p>I'm working on a website and am trying to fix how they set up their meta tags, but am having a bit of trouble.</p>
<p>The current way its set up is that all pages have the og:image set to a logo. I want two post types (post-1 and post-2) to show their respective image contained through ACF.</p>
<p>See below how it looks.</p>
<pre><code> <?php
function insert_fb_in_head() {
global $post;
if ( !is_singular())
return;
echo '<meta property="og:title" content="' . get_the_title() . '"/>';
echo '<meta property="og:type" content="article"/>';
echo '<meta property="og:url" content="' . get_permalink() . '"/>';
echo '<meta property="og:site_name" content="NewWays"/>';
if(!has_post_thumbnail( $post->ID )) {
$default_image="https://logoURLgoeshere";
echo '<meta property="og:image" content="' . $default_image . '"/>';
}
else{
$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
}
echo "
";
}
add_action( 'wp_head', 'insert_fb_in_head', 5 );
?>
</code></pre>
<p>They way they set it up with the exclamation marks in "is_singular" and "has_post_thumbnail", <em>every single page</em> on the site ends up getting that code written for the meta.</p>
<p>I'm fine with it for non-post-1 and post-2 pages, but how do I add another if statement to write the image as the meta for og:image? </p>
<p>I tried to add this but it doesn't help. Anyone have any ideas?</p>
<pre><code>function insert_og_image() {
if ( is_singular( 'post-1', 'post-2'))
$featuredImage = get_field('image');
echo '<meta property="og:image" content="' . $featuredImage . '"/>';
}
</code></pre>
| [
{
"answer_id": 355685,
"author": "websevendev",
"author_id": 180566,
"author_profile": "https://wordpress.stackexchange.com/users/180566",
"pm_score": 2,
"selected": true,
"text": "<p>First thing that jumps out is that in:</p>\n\n<p><code><!-- wp:mvc/block-mvc-offer-details {\"data_offer\":\"2426\"} /--></code></p>\n\n<p>the <code>data_offer</code> value is stored as a string while it's defined attribute type is <code>number</code>.</p>\n\n<p>This could be why it's stripped after reload. While <code>select('core').getEntityRecords</code> does return IDs as integers it's possible that after passing that data to <code><SelectControl></code> and then receiving the selected value back by it's <code>onChange(event.target.value)</code> it has lost it's type by being in the DOM.</p>\n\n<p>Try: <code>onChange={data_offer => setAttributes({data_offer: parseInt(data_offer)})}</code></p>\n"
},
{
"answer_id": 355776,
"author": "getdave",
"author_id": 26122,
"author_profile": "https://wordpress.stackexchange.com/users/26122",
"pm_score": 0,
"selected": false,
"text": "<p>You might also like to take a look at <a href=\"https://github.com/WordPress/WordPress/blob/0be749362adbf568ff250c4686320776926d0969/wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php#L63\" rel=\"nofollow noreferrer\">the REST API endpoint that handles block rendering for <code>ServerSideRender</code></a>.</p>\n\n<p>If I understand correctly from your followup post in <a href=\"https://wordpress.slack.com/archives/C02QB2JS7/p1578089674158100\" rel=\"nofollow noreferrer\">WP Slack</a> (<a href=\"https://make.wordpress.org/chat/\" rel=\"nofollow noreferrer\">registration required</a>) you want to pass down a post ID as a block attribute. In that case you need to be sure that you have a matching attribute for \"post ID\" registered for the <code>block-mvc-offer-details</code> block. This is because the REST API endpoint <code>attributes</code> argument <a href=\"https://github.com/WordPress/WordPress/blob/0be749362adbf568ff250c4686320776926d0969/wp-includes/class-wp-block-type.php#L200\" rel=\"nofollow noreferrer\">calls <code>get_attributes()</code> as it expects the attributes to match those registered on the block</a>. </p>\n"
}
] | 2020/01/03 | [
"https://wordpress.stackexchange.com/questions/355649",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177718/"
] | I'm working on a website and am trying to fix how they set up their meta tags, but am having a bit of trouble.
The current way its set up is that all pages have the og:image set to a logo. I want two post types (post-1 and post-2) to show their respective image contained through ACF.
See below how it looks.
```
<?php
function insert_fb_in_head() {
global $post;
if ( !is_singular())
return;
echo '<meta property="og:title" content="' . get_the_title() . '"/>';
echo '<meta property="og:type" content="article"/>';
echo '<meta property="og:url" content="' . get_permalink() . '"/>';
echo '<meta property="og:site_name" content="NewWays"/>';
if(!has_post_thumbnail( $post->ID )) {
$default_image="https://logoURLgoeshere";
echo '<meta property="og:image" content="' . $default_image . '"/>';
}
else{
$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
}
echo "
";
}
add_action( 'wp_head', 'insert_fb_in_head', 5 );
?>
```
They way they set it up with the exclamation marks in "is\_singular" and "has\_post\_thumbnail", *every single page* on the site ends up getting that code written for the meta.
I'm fine with it for non-post-1 and post-2 pages, but how do I add another if statement to write the image as the meta for og:image?
I tried to add this but it doesn't help. Anyone have any ideas?
```
function insert_og_image() {
if ( is_singular( 'post-1', 'post-2'))
$featuredImage = get_field('image');
echo '<meta property="og:image" content="' . $featuredImage . '"/>';
}
``` | First thing that jumps out is that in:
`<!-- wp:mvc/block-mvc-offer-details {"data_offer":"2426"} /-->`
the `data_offer` value is stored as a string while it's defined attribute type is `number`.
This could be why it's stripped after reload. While `select('core').getEntityRecords` does return IDs as integers it's possible that after passing that data to `<SelectControl>` and then receiving the selected value back by it's `onChange(event.target.value)` it has lost it's type by being in the DOM.
Try: `onChange={data_offer => setAttributes({data_offer: parseInt(data_offer)})}` |
355,670 | <p>I have this function in my functions.php file:</p>
<pre><code>function dns_prefetch_to_preconnect( $urls, $relation_type ) {
if ( 'dns-prefetch' === $relation_type ) {
$urls = [];
}
if ( 'preconnect' === $relation_type ) {
$urls = wp_dependencies_unique_hosts();
}
return $urls;
}
add_filter( 'wp_resource_hints', 'dns_prefetch_to_preconnect', 0, 2 );
</code></pre>
<p>It takes the URLs defined in <code>wp_dependencies_unique_hosts()</code> – which WordPress by default assigns to the <code>dns-prefetch</code> link tag – and reassigns them to the <code>preconnect</code> link tag. The function was provided to me here:</p>
<p><a href="https://wordpress.stackexchange.com/questions/345533/change-dns-prefetch-to-preconnect-for-external-enqueued-resources">Change dns-prefetch to preconnect for external enqueued resources</a></p>
<p>However, this function isn't working entirely correctly. It adds the <code>preconnect</code> URLs using http instead of https.</p>
<p>Example: when I'm not using the above function, WordPress adds this link to my header:</p>
<pre><code><link rel='dns-prefetch' href='//fonts.googleapis.com' />
</code></pre>
<p>And when I enable the above function, it replaces that link with this link:</p>
<pre><code><link rel='preconnect' href='http://fonts.googleapis.com' />
</code></pre>
<p>The problem, of course, is that it should be https, not http.</p>
<p>Can someone help me modify my function so that it gives me https links?</p>
| [
{
"answer_id": 355673,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is not that the function you're using adds <code>http:</code>, the problem is it adds no URL schema at all!</p>\n\n<p>As a result, WP needs to add a URL schema to turn the host into a URL, and so it uses <code>http://</code>. It has no way of knowing what the original was, or if the host supports HTTPS, so <code>http://</code> is the safe bet.</p>\n\n<p>If however you passed the array with URL schema added, it would be passed through without issue.</p>\n\n<p>Something like this may do the trick:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$hosts = wp_dependencies_unique_hosts();\n$urls = array_map( function( $host ) {\n return set_url_scheme( $host, 'https' );\n}, $hosts );\n</code></pre>\n\n<p>In the longrun though, it would be better to get the actual URLs and distill the host URL out of them, rather than relying on <code>wp_dependencies_unique_hosts</code> if you wanted to preserve the mixture of <code>http</code> and <code>https</code></p>\n"
},
{
"answer_id": 355839,
"author": "GermanKiwi",
"author_id": 58939,
"author_profile": "https://wordpress.stackexchange.com/users/58939",
"pm_score": 1,
"selected": true,
"text": "<p>I've finally got it working now, as follows:</p>\n\n<p>First I found the original <code>wp_dependencies_unique_hosts()</code> function from the WordPress code (it's in a file called general-template.php), and I made a copy of it, but giving it a new name: <code>wp_dependencies_unique_urls()</code>.</p>\n\n<p>I observed that this function is using <code>wp_parse_url()</code> to grab just the host part of each URL from the list of scripts and styles. In other words, it's dropping the scheme, which is the reason for the problem I'm having.</p>\n\n<p>So I modified the function to include the scheme - here it is in its entirety:</p>\n\n<pre><code>function wp_dependencies_unique_urls() {\n global $wp_scripts, $wp_styles;\n\n $unique_urls = array();\n\n foreach ( array( $wp_scripts, $wp_styles ) as $dependencies ) {\n if ( $dependencies instanceof WP_Dependencies && ! empty( $dependencies->queue ) ) {\n foreach ( $dependencies->queue as $handle ) {\n if ( ! isset( $dependencies->registered[ $handle ] ) ) {\n continue;\n }\n\n $dependency = $dependencies->registered[ $handle ];\n $parsed = wp_parse_url( $dependency->src );\n\n if ( ! empty( $parsed['host'] ) && ! in_array( $parsed['host'], $unique_urls ) && $parsed['host'] !== $_SERVER['SERVER_NAME'] ) {\n $unique_urls[] = $parsed['scheme'] . '://' . $parsed['host'];\n }\n }\n }\n }\n\n return $unique_urls;\n}\n</code></pre>\n\n<p>As you can see, the main thing I've changed is this:</p>\n\n<pre><code>$unique_urls[] = $parsed['scheme'] . '://' . $parsed['host'];\n</code></pre>\n\n<p>I hope this is the best way to add the scheme to the beginning of each URL.</p>\n\n<p>Next, I modified my original function (from my original question above) so it calls this new function I've created:</p>\n\n<pre><code>function dns_prefetch_to_preconnect( $urls, $relation_type ) {\n\n if ( 'dns-prefetch' === $relation_type ) {\n $urls = [];\n }\n\n if ( 'preconnect' === $relation_type ) {\n $urls = wp_dependencies_unique_urls();\n }\n\n return $urls;\n}\nadd_filter( 'wp_resource_hints', 'dns_prefetch_to_preconnect', 0, 2 );\n</code></pre>\n\n<p>Et voila, it works! I now have valid 'preconnect' links in my page headers, which use the same scheme as the original enqueued scripts and styles - either http or https!</p>\n\n<p>And if I want to, I can combine my two functions into one big function for simplicity:</p>\n\n<pre><code>function dns_prefetch_to_preconnect( $urls, $relation_type ) {\n global $wp_scripts, $wp_styles;\n\n $unique_urls = array();\n\n foreach ( array( $wp_scripts, $wp_styles ) as $dependencies ) {\n if ( $dependencies instanceof WP_Dependencies && ! empty( $dependencies->queue ) ) {\n foreach ( $dependencies->queue as $handle ) {\n if ( ! isset( $dependencies->registered[ $handle ] ) ) {\n continue;\n }\n\n $dependency = $dependencies->registered[ $handle ];\n $parsed = wp_parse_url( $dependency->src );\n\n if ( ! empty( $parsed['host'] ) && ! in_array( $parsed['host'], $unique_urls ) && $parsed['host'] !== $_SERVER['SERVER_NAME'] ) {\n $unique_urls[] = $parsed['scheme'] . '://' . $parsed['host'];\n }\n }\n }\n }\n\n if ( 'dns-prefetch' === $relation_type ) {\n $urls = [];\n }\n\n if ( 'preconnect' === $relation_type ) {\n $urls = $unique_urls;\n }\n\n return $urls;\n}\nadd_filter( 'wp_resource_hints', 'dns_prefetch_to_preconnect', 0, 2 );\n</code></pre>\n"
}
] | 2020/01/04 | [
"https://wordpress.stackexchange.com/questions/355670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58939/"
] | I have this function in my functions.php file:
```
function dns_prefetch_to_preconnect( $urls, $relation_type ) {
if ( 'dns-prefetch' === $relation_type ) {
$urls = [];
}
if ( 'preconnect' === $relation_type ) {
$urls = wp_dependencies_unique_hosts();
}
return $urls;
}
add_filter( 'wp_resource_hints', 'dns_prefetch_to_preconnect', 0, 2 );
```
It takes the URLs defined in `wp_dependencies_unique_hosts()` – which WordPress by default assigns to the `dns-prefetch` link tag – and reassigns them to the `preconnect` link tag. The function was provided to me here:
[Change dns-prefetch to preconnect for external enqueued resources](https://wordpress.stackexchange.com/questions/345533/change-dns-prefetch-to-preconnect-for-external-enqueued-resources)
However, this function isn't working entirely correctly. It adds the `preconnect` URLs using http instead of https.
Example: when I'm not using the above function, WordPress adds this link to my header:
```
<link rel='dns-prefetch' href='//fonts.googleapis.com' />
```
And when I enable the above function, it replaces that link with this link:
```
<link rel='preconnect' href='http://fonts.googleapis.com' />
```
The problem, of course, is that it should be https, not http.
Can someone help me modify my function so that it gives me https links? | I've finally got it working now, as follows:
First I found the original `wp_dependencies_unique_hosts()` function from the WordPress code (it's in a file called general-template.php), and I made a copy of it, but giving it a new name: `wp_dependencies_unique_urls()`.
I observed that this function is using `wp_parse_url()` to grab just the host part of each URL from the list of scripts and styles. In other words, it's dropping the scheme, which is the reason for the problem I'm having.
So I modified the function to include the scheme - here it is in its entirety:
```
function wp_dependencies_unique_urls() {
global $wp_scripts, $wp_styles;
$unique_urls = array();
foreach ( array( $wp_scripts, $wp_styles ) as $dependencies ) {
if ( $dependencies instanceof WP_Dependencies && ! empty( $dependencies->queue ) ) {
foreach ( $dependencies->queue as $handle ) {
if ( ! isset( $dependencies->registered[ $handle ] ) ) {
continue;
}
$dependency = $dependencies->registered[ $handle ];
$parsed = wp_parse_url( $dependency->src );
if ( ! empty( $parsed['host'] ) && ! in_array( $parsed['host'], $unique_urls ) && $parsed['host'] !== $_SERVER['SERVER_NAME'] ) {
$unique_urls[] = $parsed['scheme'] . '://' . $parsed['host'];
}
}
}
}
return $unique_urls;
}
```
As you can see, the main thing I've changed is this:
```
$unique_urls[] = $parsed['scheme'] . '://' . $parsed['host'];
```
I hope this is the best way to add the scheme to the beginning of each URL.
Next, I modified my original function (from my original question above) so it calls this new function I've created:
```
function dns_prefetch_to_preconnect( $urls, $relation_type ) {
if ( 'dns-prefetch' === $relation_type ) {
$urls = [];
}
if ( 'preconnect' === $relation_type ) {
$urls = wp_dependencies_unique_urls();
}
return $urls;
}
add_filter( 'wp_resource_hints', 'dns_prefetch_to_preconnect', 0, 2 );
```
Et voila, it works! I now have valid 'preconnect' links in my page headers, which use the same scheme as the original enqueued scripts and styles - either http or https!
And if I want to, I can combine my two functions into one big function for simplicity:
```
function dns_prefetch_to_preconnect( $urls, $relation_type ) {
global $wp_scripts, $wp_styles;
$unique_urls = array();
foreach ( array( $wp_scripts, $wp_styles ) as $dependencies ) {
if ( $dependencies instanceof WP_Dependencies && ! empty( $dependencies->queue ) ) {
foreach ( $dependencies->queue as $handle ) {
if ( ! isset( $dependencies->registered[ $handle ] ) ) {
continue;
}
$dependency = $dependencies->registered[ $handle ];
$parsed = wp_parse_url( $dependency->src );
if ( ! empty( $parsed['host'] ) && ! in_array( $parsed['host'], $unique_urls ) && $parsed['host'] !== $_SERVER['SERVER_NAME'] ) {
$unique_urls[] = $parsed['scheme'] . '://' . $parsed['host'];
}
}
}
}
if ( 'dns-prefetch' === $relation_type ) {
$urls = [];
}
if ( 'preconnect' === $relation_type ) {
$urls = $unique_urls;
}
return $urls;
}
add_filter( 'wp_resource_hints', 'dns_prefetch_to_preconnect', 0, 2 );
``` |
355,694 | <p>I want show the avatar user and username with this code.</p>
<pre><code>add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( strpos($menu_item->title, '#profile_name#') !== false) {
$menu_item->title = str_replace("#profile_name#", wp_get_current_user()->user_login, $menu_item->title);
}
}
return $menu_items;
}
</code></pre>
<p>The username is work but i don't known add avatar.</p>
<p>Can you help me please</p>
| [
{
"answer_id": 355771,
"author": "Bhupen",
"author_id": 128529,
"author_profile": "https://wordpress.stackexchange.com/users/128529",
"pm_score": 1,
"selected": false,
"text": "<p>You can use \"<strong>get_avatar</strong>\" function to display avatar in menu with user name. Please try code given below:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items', 10 );\nfunction my_dynamic_menu_items( $menu_items ) {\n foreach ( $menu_items as $menu_item ) {\n if ( strpos($menu_item->title, '#profile_name#') !== false) {\n $menu_item->title = str_replace(\"#profile_name#\", wp_get_current_user()->user_login .' '. get_avatar( wp_get_current_user()->user_email, 50), $menu_item->title);\n }\n }\n return $menu_items;\n}\n</code></pre>\n"
},
{
"answer_id": 365640,
"author": "Jerry S",
"author_id": 187304,
"author_profile": "https://wordpress.stackexchange.com/users/187304",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a tiny plugin to do just this as I didn't find a nice wordpressy way of doing it. I intend it to work across different themes and with different membership plugins. I have been using Ultimate Member on Divi theme. Feel free to use it or adapt it as required. I hope that you find it helpful: \n<a href=\"https://wordpress.org/plugins/logged-in-as/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/logged-in-as/</a></p>\n"
}
] | 2020/01/04 | [
"https://wordpress.stackexchange.com/questions/355694",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180573/"
] | I want show the avatar user and username with this code.
```
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( strpos($menu_item->title, '#profile_name#') !== false) {
$menu_item->title = str_replace("#profile_name#", wp_get_current_user()->user_login, $menu_item->title);
}
}
return $menu_items;
}
```
The username is work but i don't known add avatar.
Can you help me please | You can use "**get\_avatar**" function to display avatar in menu with user name. Please try code given below:
```
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items', 10 );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( strpos($menu_item->title, '#profile_name#') !== false) {
$menu_item->title = str_replace("#profile_name#", wp_get_current_user()->user_login .' '. get_avatar( wp_get_current_user()->user_email, 50), $menu_item->title);
}
}
return $menu_items;
}
``` |
355,699 | <p>I'm trying to remove the entire <a href="https://developer.wordpress.org/reference/hooks/embed_footer/" rel="nofollow noreferrer">embed_footer</a> from WordPress embedded posts.</p>
<p>By adding the following code in the <code>functions.php</code>, I was able to remove the site title and comments icon. But still, the share icon is there.</p>
<pre><code>add_filter('embed_site_title_html','__return_false');
remove_action( 'embed_content_meta', 'print_embed_comments_button' );
</code></pre>
<p>Is there a way to remove the entire <code>embed_footer</code>? Or can I remove the share button also like the above code?</p>
| [
{
"answer_id": 355700,
"author": "Ahmedhere",
"author_id": 180546,
"author_profile": "https://wordpress.stackexchange.com/users/180546",
"pm_score": -1,
"selected": false,
"text": "<p>All the javascript files are embedded in the footer if you remove the footer maybe your site goes down. There are two ways:</p>\n\n<ol>\n<li>Create a child theme and create footer.php and call <code>wp_footer();</code> hook there.</li>\n<li>Or If you just want to remove the footer text you can do this in CSS just find the class or id and make it <code>display: none;</code></li>\n</ol>\n"
},
{
"answer_id": 402074,
"author": "Brett Donald",
"author_id": 143573,
"author_profile": "https://wordpress.stackexchange.com/users/143573",
"pm_score": 0,
"selected": false,
"text": "<p>The comments button and the share button are generated in two separate default actions, so you have to remove them both:</p>\n<pre><code>remove_action( 'embed_content_meta', 'print_embed_comments_button' );\nremove_action( 'embed_content_meta', 'print_embed_sharing_button' );\n</code></pre>\n"
}
] | 2020/01/04 | [
"https://wordpress.stackexchange.com/questions/355699",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12611/"
] | I'm trying to remove the entire [embed\_footer](https://developer.wordpress.org/reference/hooks/embed_footer/) from WordPress embedded posts.
By adding the following code in the `functions.php`, I was able to remove the site title and comments icon. But still, the share icon is there.
```
add_filter('embed_site_title_html','__return_false');
remove_action( 'embed_content_meta', 'print_embed_comments_button' );
```
Is there a way to remove the entire `embed_footer`? Or can I remove the share button also like the above code? | The comments button and the share button are generated in two separate default actions, so you have to remove them both:
```
remove_action( 'embed_content_meta', 'print_embed_comments_button' );
remove_action( 'embed_content_meta', 'print_embed_sharing_button' );
``` |
355,734 | <p>I have a class for registering post types based on the Wordpress Plugin Boiler Plate, in the below can anyone tell me why the taxonomy isn't showing in the admin menus at all?</p>
<pre><code>/**
* Register custom post type
*
*/
class Hi_Food_Menu_Post_Types {
/**
* Register custom post type
*
* @link https://codex.wordpress.org/Function_Reference/register_post_type
*/
private function register_single_post_type( $fields ) {
/**
* Labels used when displaying the posts in the admin and sometimes on the front end. These
* labels do not cover post updated, error, and related messages. You'll need to filter the
* 'post_updated_messages' hook to customize those.
*/
$labels = array(
'name' => $fields['plural'],
'singular_name' => $fields['singular'],
'menu_name' => $fields['menu_name'],
'new_item' => sprintf( __( 'New %s', 'plugin-name' ), $fields['singular'] ),
'add_new_item' => sprintf( __( 'Add new %s', 'plugin-name' ), $fields['singular'] ),
'edit_item' => sprintf( __( 'Edit %s', 'plugin-name' ), $fields['singular'] ),
'view_item' => sprintf( __( 'View %s', 'plugin-name' ), $fields['singular'] ),
'view_items' => sprintf( __( 'View %s', 'plugin-name' ), $fields['plural'] ),
'search_items' => sprintf( __( 'Search %s', 'plugin-name' ), $fields['plural'] ),
'not_found' => sprintf( __( 'No %s found', 'plugin-name' ), strtolower( $fields['plural'] ) ),
'not_found_in_trash' => sprintf( __( 'No %s found in trash', 'plugin-name' ), strtolower( $fields['plural'] ) ),
'all_items' => sprintf( __( 'All %s', 'plugin-name' ), $fields['plural'] ),
'archives' => sprintf( __( '%s Archives', 'plugin-name' ), $fields['singular'] ),
'attributes' => sprintf( __( '%s Attributes', 'plugin-name' ), $fields['singular'] ),
'insert_into_item' => sprintf( __( 'Insert into %s', 'plugin-name' ), strtolower( $fields['singular'] ) ),
'uploaded_to_this_item' => sprintf( __( 'Uploaded to this %s', 'plugin-name' ), strtolower( $fields['singular'] ) ),
/* Labels for hierarchical post types only. */
'parent_item' => sprintf( __( 'Parent %s', 'plugin-name' ), $fields['singular'] ),
'parent_item_colon' => sprintf( __( 'Parent %s:', 'plugin-name' ), $fields['singular'] ),
/* Custom archive label. Must filter 'post_type_archive_title' to use. */
'archive_title' => $fields['plural'],
);
$args = array(
'labels' => $labels,
'description' => ( isset( $fields['description'] ) ) ? $fields['description'] : '',
'public' => ( isset( $fields['public'] ) ) ? $fields['public'] : true,
'publicly_queryable' => ( isset( $fields['publicly_queryable'] ) ) ? $fields['publicly_queryable'] : true,
'exclude_from_search'=> ( isset( $fields['exclude_from_search'] ) ) ? $fields['exclude_from_search'] : false,
'show_ui' => ( isset( $fields['show_ui'] ) ) ? $fields['show_ui'] : true,
'show_in_menu' => ( isset( $fields['show_in_menu'] ) ) ? $fields['show_in_menu'] : true,
'query_var' => ( isset( $fields['query_var'] ) ) ? $fields['query_var'] : true,
'show_in_admin_bar' => ( isset( $fields['show_in_admin_bar'] ) ) ? $fields['show_in_admin_bar'] : true,
'capability_type' => ( isset( $fields['capability_type'] ) ) ? $fields['capability_type'] : 'post',
'has_archive' => ( isset( $fields['has_archive'] ) ) ? $fields['has_archive'] : true,
'hierarchical' => ( isset( $fields['hierarchical'] ) ) ? $fields['hierarchical'] : true,
'supports' => ( isset( $fields['supports'] ) ) ? $fields['supports'] : array(
'title',
'editor',
'excerpt',
'author',
'thumbnail',
'comments',
'trackbacks',
'custom-fields',
'revisions',
'page-attributes',
'post-formats',
),
'menu_position' => ( isset( $fields['menu_position'] ) ) ? $fields['menu_position'] : 21,
'menu_icon' => ( isset( $fields['menu_icon'] ) ) ? $fields['menu_icon']: 'dashicons-admin-generic',
'show_in_nav_menus' => ( isset( $fields['show_in_nav_menus'] ) ) ? $fields['show_in_nav_menus'] : true,
);
if ( isset( $fields['rewrite'] ) ) {
/**
* Add $this->plugin_name as translatable in the permalink structure,
* to avoid conflicts with other plugins which may use customers as well.
*/
$args['rewrite'] = $fields['rewrite'];
}
if ( $fields['custom_caps'] ) {
/**
* Provides more precise control over the capabilities than the defaults. By default, WordPress
* will use the 'capability_type' argument to build these capabilities. More often than not,
* this results in many extra capabilities that you probably don't need. The following is how
* I set up capabilities for many post types, which only uses three basic capabilities you need
* to assign to roles: 'manage_examples', 'edit_examples', 'create_examples'. Each post type
* is unique though, so you'll want to adjust it to fit your needs.
*
* @link https://gist.github.com/creativembers/6577149
* @link http://justintadlock.com/archives/2010/07/10/meta-capabilities-for-custom-post-types
*/
$args['capabilities'] = array(
// Meta capabilities
'edit_post' => 'edit_' . strtolower( $fields['singular'] ),
'read_post' => 'read_' . strtolower( $fields['singular'] ),
'delete_post' => 'delete_' . strtolower( $fields['singular'] ),
// Primitive capabilities used outside of map_meta_cap():
'edit_posts' => 'edit_' . strtolower( $fields['plural'] ),
'edit_others_posts' => 'edit_others_' . strtolower( $fields['plural'] ),
'publish_posts' => 'publish_' . strtolower( $fields['plural'] ),
'read_private_posts' => 'read_private_' . strtolower( $fields['plural'] ),
// Primitive capabilities used within map_meta_cap():
'delete_posts' => 'delete_' . strtolower( $fields['plural'] ),
'delete_private_posts' => 'delete_private_' . strtolower( $fields['plural'] ),
'delete_published_posts' => 'delete_published_' . strtolower( $fields['plural'] ),
'delete_others_posts' => 'delete_others_' . strtolower( $fields['plural'] ),
'edit_private_posts' => 'edit_private_' . strtolower( $fields['plural'] ),
'edit_published_posts' => 'edit_published_' . strtolower( $fields['plural'] ),
'create_posts' => 'edit_' . strtolower( $fields['plural'] )
);
/**
* Adding map_meta_cap will map the meta correctly.
* @link https://wordpress.stackexchange.com/questions/108338/capabilities-and-custom-post-types/108375#108375
*/
$args['map_meta_cap'] = true;
/**
* Assign capabilities to users
* Without this, users - also admins - can not see post type.
*/
$this->assign_capabilities( $args['capabilities'], $fields['custom_caps_users'] );
}
register_post_type( $fields['slug'], $args );
/**
* Register Taxnonmies if any
* @link https://codex.wordpress.org/Function_Reference/register_taxonomy
*/
if ( isset( $fields['taxonomies'] ) && is_array( $fields['taxonomies'] ) ) {
foreach ( $fields['taxonomies'] as $taxonomy ) {
$this->register_single_post_type_taxnonomy( $taxonomy );
}
}
}
private function register_single_post_type_taxnonomy( $tax_fields ) {
$labels = array(
'name' => $tax_fields['plural'],
'singular_name' => $tax_fields['single'],
'menu_name' => $tax_fields['plural'],
'all_items' => sprintf( __( 'All %s' , 'plugin-name' ), $tax_fields['plural'] ),
'edit_item' => sprintf( __( 'Edit %s' , 'plugin-name' ), $tax_fields['single'] ),
'view_item' => sprintf( __( 'View %s' , 'plugin-name' ), $tax_fields['single'] ),
'update_item' => sprintf( __( 'Update %s' , 'plugin-name' ), $tax_fields['single'] ),
'add_new_item' => sprintf( __( 'Add New %s' , 'plugin-name' ), $tax_fields['single'] ),
'new_item_name' => sprintf( __( 'New %s Name' , 'plugin-name' ), $tax_fields['single'] ),
'parent_item' => sprintf( __( 'Parent %s' , 'plugin-name' ), $tax_fields['single'] ),
'parent_item_colon' => sprintf( __( 'Parent %s:' , 'plugin-name' ), $tax_fields['single'] ),
'search_items' => sprintf( __( 'Search %s' , 'plugin-name' ), $tax_fields['plural'] ),
'popular_items' => sprintf( __( 'Popular %s' , 'plugin-name' ), $tax_fields['plural'] ),
'separate_items_with_commas' => sprintf( __( 'Separate %s with commas' , 'plugin-name' ), $tax_fields['plural'] ),
'add_or_remove_items' => sprintf( __( 'Add or remove %s' , 'plugin-name' ), $tax_fields['plural'] ),
'choose_from_most_used' => sprintf( __( 'Choose from the most used %s' , 'plugin-name' ), $tax_fields['plural'] ),
'not_found' => sprintf( __( 'No %s found' , 'plugin-name' ), $tax_fields['plural'] ),
);
$args = array(
'label' => $tax_fields['plural'],
'labels' => $labels,
'hierarchical' => ( isset( $tax_fields['hierarchical'] ) ) ? $tax_fields['hierarchical'] : true,
'public' => ( isset( $tax_fields['public'] ) ) ? $tax_fields['public'] : true,
'show_ui' => ( isset( $tax_fields['show_ui'] ) ) ? $tax_fields['show_ui'] : true,
'show_in_nav_menus' => ( isset( $tax_fields['show_in_nav_menus'] ) ) ? $tax_fields['show_in_nav_menus'] : true,
'show_tagcloud' => ( isset( $tax_fields['show_tagcloud'] ) ) ? $tax_fields['show_tagcloud'] : true,
'meta_box_cb' => ( isset( $tax_fields['meta_box_cb'] ) ) ? $tax_fields['meta_box_cb'] : null,
'show_admin_column' => ( isset( $tax_fields['show_admin_column'] ) ) ? $tax_fields['show_admin_column'] : true,
'show_in_quick_edit' => ( isset( $tax_fields['show_in_quick_edit'] ) ) ? $tax_fields['show_in_quick_edit'] : true,
'update_count_callback' => ( isset( $tax_fields['update_count_callback'] ) ) ? $tax_fields['update_count_callback'] : '',
'show_in_rest' => ( isset( $tax_fields['show_in_rest'] ) ) ? $tax_fields['show_in_rest'] : true,
'rest_base' => $tax_fields['taxonomy'],
'rest_controller_class' => ( isset( $tax_fields['rest_controller_class'] ) ) ? $tax_fields['rest_controller_class'] : 'WP_REST_Terms_Controller',
'query_var' => $tax_fields['taxonomy'],
'rewrite' => ( isset( $tax_fields['rewrite'] ) ) ? $tax_fields['rewrite'] : true,
'sort' => ( isset( $tax_fields['sort'] ) ) ? $tax_fields['sort'] : '',
);
$args = apply_filters( $tax_fields['taxonomy'] . '_args', $args );
register_taxonomy( $tax_fields['taxonomy'], $tax_fields['post_types'], $args );
}
/**
* Assign capabilities to users
*
* @link https://codex.wordpress.org/Function_Reference/register_post_type
* @link https://typerocket.com/ultimate-guide-to-custom-post-types-in-wordpress/
*/
public function assign_capabilities( $caps_map, $users ) {
foreach ( $users as $user ) {
$user_role = get_role( $user );
foreach ( $caps_map as $cap_map_key => $capability ) {
$user_role->add_cap( $capability );
}
}
}
/**
* CUSTOMIZE CUSTOM POST TYPE AS YOU WISH.
*/
/**
* Create post types
*/
public function create_custom_post_type() {
$food_menu_item_fields = array(
array(
'slug' => 'food-menu-item',
'singular' => 'Food Menu Item',
'plural' => 'Food Menu Items',
'menu_name' => 'Food Menu Items',
'description' => 'Food Menu Items',
'has_archive' => true,
'hierarchical' => false,
'menu_icon' => 'dashicons-carrot',
'rewrite' => array(
'slug' => 'food-menu-items',
'with_front' => true,
'pages' => true,
'feeds' => true,
'ep_mask' => EP_PERMALINK,
),
'menu_position' => 21,
'public' => true,
'publicly_queryable' => true,
'exclude_from_search' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'supports' => array(
'title',
'editor',
'excerpt',
'author',
'thumbnail',
'comments',
'trackbacks',
'custom-fields',
'revisions',
'page-attributes',
'post-formats',
),
'custom_caps' => true,
'custom_caps_users' => array(
'administrator',
),
'taxonomies' => array(
array(
'taxonomy' => 'food_menu_item_category',
'plural' => 'Food Menu Item Categories',
'single' => 'Food Menu Item Category',
'post_types' => array( 'Food Menu Item' ),
),
),
),
);
foreach ( $food_menu_item_fields as $fields ) {
$this->register_single_post_type( $fields );
}
// ...
}
// ...
}
?>
</code></pre>
| [
{
"answer_id": 355700,
"author": "Ahmedhere",
"author_id": 180546,
"author_profile": "https://wordpress.stackexchange.com/users/180546",
"pm_score": -1,
"selected": false,
"text": "<p>All the javascript files are embedded in the footer if you remove the footer maybe your site goes down. There are two ways:</p>\n\n<ol>\n<li>Create a child theme and create footer.php and call <code>wp_footer();</code> hook there.</li>\n<li>Or If you just want to remove the footer text you can do this in CSS just find the class or id and make it <code>display: none;</code></li>\n</ol>\n"
},
{
"answer_id": 402074,
"author": "Brett Donald",
"author_id": 143573,
"author_profile": "https://wordpress.stackexchange.com/users/143573",
"pm_score": 0,
"selected": false,
"text": "<p>The comments button and the share button are generated in two separate default actions, so you have to remove them both:</p>\n<pre><code>remove_action( 'embed_content_meta', 'print_embed_comments_button' );\nremove_action( 'embed_content_meta', 'print_embed_sharing_button' );\n</code></pre>\n"
}
] | 2020/01/05 | [
"https://wordpress.stackexchange.com/questions/355734",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/161436/"
] | I have a class for registering post types based on the Wordpress Plugin Boiler Plate, in the below can anyone tell me why the taxonomy isn't showing in the admin menus at all?
```
/**
* Register custom post type
*
*/
class Hi_Food_Menu_Post_Types {
/**
* Register custom post type
*
* @link https://codex.wordpress.org/Function_Reference/register_post_type
*/
private function register_single_post_type( $fields ) {
/**
* Labels used when displaying the posts in the admin and sometimes on the front end. These
* labels do not cover post updated, error, and related messages. You'll need to filter the
* 'post_updated_messages' hook to customize those.
*/
$labels = array(
'name' => $fields['plural'],
'singular_name' => $fields['singular'],
'menu_name' => $fields['menu_name'],
'new_item' => sprintf( __( 'New %s', 'plugin-name' ), $fields['singular'] ),
'add_new_item' => sprintf( __( 'Add new %s', 'plugin-name' ), $fields['singular'] ),
'edit_item' => sprintf( __( 'Edit %s', 'plugin-name' ), $fields['singular'] ),
'view_item' => sprintf( __( 'View %s', 'plugin-name' ), $fields['singular'] ),
'view_items' => sprintf( __( 'View %s', 'plugin-name' ), $fields['plural'] ),
'search_items' => sprintf( __( 'Search %s', 'plugin-name' ), $fields['plural'] ),
'not_found' => sprintf( __( 'No %s found', 'plugin-name' ), strtolower( $fields['plural'] ) ),
'not_found_in_trash' => sprintf( __( 'No %s found in trash', 'plugin-name' ), strtolower( $fields['plural'] ) ),
'all_items' => sprintf( __( 'All %s', 'plugin-name' ), $fields['plural'] ),
'archives' => sprintf( __( '%s Archives', 'plugin-name' ), $fields['singular'] ),
'attributes' => sprintf( __( '%s Attributes', 'plugin-name' ), $fields['singular'] ),
'insert_into_item' => sprintf( __( 'Insert into %s', 'plugin-name' ), strtolower( $fields['singular'] ) ),
'uploaded_to_this_item' => sprintf( __( 'Uploaded to this %s', 'plugin-name' ), strtolower( $fields['singular'] ) ),
/* Labels for hierarchical post types only. */
'parent_item' => sprintf( __( 'Parent %s', 'plugin-name' ), $fields['singular'] ),
'parent_item_colon' => sprintf( __( 'Parent %s:', 'plugin-name' ), $fields['singular'] ),
/* Custom archive label. Must filter 'post_type_archive_title' to use. */
'archive_title' => $fields['plural'],
);
$args = array(
'labels' => $labels,
'description' => ( isset( $fields['description'] ) ) ? $fields['description'] : '',
'public' => ( isset( $fields['public'] ) ) ? $fields['public'] : true,
'publicly_queryable' => ( isset( $fields['publicly_queryable'] ) ) ? $fields['publicly_queryable'] : true,
'exclude_from_search'=> ( isset( $fields['exclude_from_search'] ) ) ? $fields['exclude_from_search'] : false,
'show_ui' => ( isset( $fields['show_ui'] ) ) ? $fields['show_ui'] : true,
'show_in_menu' => ( isset( $fields['show_in_menu'] ) ) ? $fields['show_in_menu'] : true,
'query_var' => ( isset( $fields['query_var'] ) ) ? $fields['query_var'] : true,
'show_in_admin_bar' => ( isset( $fields['show_in_admin_bar'] ) ) ? $fields['show_in_admin_bar'] : true,
'capability_type' => ( isset( $fields['capability_type'] ) ) ? $fields['capability_type'] : 'post',
'has_archive' => ( isset( $fields['has_archive'] ) ) ? $fields['has_archive'] : true,
'hierarchical' => ( isset( $fields['hierarchical'] ) ) ? $fields['hierarchical'] : true,
'supports' => ( isset( $fields['supports'] ) ) ? $fields['supports'] : array(
'title',
'editor',
'excerpt',
'author',
'thumbnail',
'comments',
'trackbacks',
'custom-fields',
'revisions',
'page-attributes',
'post-formats',
),
'menu_position' => ( isset( $fields['menu_position'] ) ) ? $fields['menu_position'] : 21,
'menu_icon' => ( isset( $fields['menu_icon'] ) ) ? $fields['menu_icon']: 'dashicons-admin-generic',
'show_in_nav_menus' => ( isset( $fields['show_in_nav_menus'] ) ) ? $fields['show_in_nav_menus'] : true,
);
if ( isset( $fields['rewrite'] ) ) {
/**
* Add $this->plugin_name as translatable in the permalink structure,
* to avoid conflicts with other plugins which may use customers as well.
*/
$args['rewrite'] = $fields['rewrite'];
}
if ( $fields['custom_caps'] ) {
/**
* Provides more precise control over the capabilities than the defaults. By default, WordPress
* will use the 'capability_type' argument to build these capabilities. More often than not,
* this results in many extra capabilities that you probably don't need. The following is how
* I set up capabilities for many post types, which only uses three basic capabilities you need
* to assign to roles: 'manage_examples', 'edit_examples', 'create_examples'. Each post type
* is unique though, so you'll want to adjust it to fit your needs.
*
* @link https://gist.github.com/creativembers/6577149
* @link http://justintadlock.com/archives/2010/07/10/meta-capabilities-for-custom-post-types
*/
$args['capabilities'] = array(
// Meta capabilities
'edit_post' => 'edit_' . strtolower( $fields['singular'] ),
'read_post' => 'read_' . strtolower( $fields['singular'] ),
'delete_post' => 'delete_' . strtolower( $fields['singular'] ),
// Primitive capabilities used outside of map_meta_cap():
'edit_posts' => 'edit_' . strtolower( $fields['plural'] ),
'edit_others_posts' => 'edit_others_' . strtolower( $fields['plural'] ),
'publish_posts' => 'publish_' . strtolower( $fields['plural'] ),
'read_private_posts' => 'read_private_' . strtolower( $fields['plural'] ),
// Primitive capabilities used within map_meta_cap():
'delete_posts' => 'delete_' . strtolower( $fields['plural'] ),
'delete_private_posts' => 'delete_private_' . strtolower( $fields['plural'] ),
'delete_published_posts' => 'delete_published_' . strtolower( $fields['plural'] ),
'delete_others_posts' => 'delete_others_' . strtolower( $fields['plural'] ),
'edit_private_posts' => 'edit_private_' . strtolower( $fields['plural'] ),
'edit_published_posts' => 'edit_published_' . strtolower( $fields['plural'] ),
'create_posts' => 'edit_' . strtolower( $fields['plural'] )
);
/**
* Adding map_meta_cap will map the meta correctly.
* @link https://wordpress.stackexchange.com/questions/108338/capabilities-and-custom-post-types/108375#108375
*/
$args['map_meta_cap'] = true;
/**
* Assign capabilities to users
* Without this, users - also admins - can not see post type.
*/
$this->assign_capabilities( $args['capabilities'], $fields['custom_caps_users'] );
}
register_post_type( $fields['slug'], $args );
/**
* Register Taxnonmies if any
* @link https://codex.wordpress.org/Function_Reference/register_taxonomy
*/
if ( isset( $fields['taxonomies'] ) && is_array( $fields['taxonomies'] ) ) {
foreach ( $fields['taxonomies'] as $taxonomy ) {
$this->register_single_post_type_taxnonomy( $taxonomy );
}
}
}
private function register_single_post_type_taxnonomy( $tax_fields ) {
$labels = array(
'name' => $tax_fields['plural'],
'singular_name' => $tax_fields['single'],
'menu_name' => $tax_fields['plural'],
'all_items' => sprintf( __( 'All %s' , 'plugin-name' ), $tax_fields['plural'] ),
'edit_item' => sprintf( __( 'Edit %s' , 'plugin-name' ), $tax_fields['single'] ),
'view_item' => sprintf( __( 'View %s' , 'plugin-name' ), $tax_fields['single'] ),
'update_item' => sprintf( __( 'Update %s' , 'plugin-name' ), $tax_fields['single'] ),
'add_new_item' => sprintf( __( 'Add New %s' , 'plugin-name' ), $tax_fields['single'] ),
'new_item_name' => sprintf( __( 'New %s Name' , 'plugin-name' ), $tax_fields['single'] ),
'parent_item' => sprintf( __( 'Parent %s' , 'plugin-name' ), $tax_fields['single'] ),
'parent_item_colon' => sprintf( __( 'Parent %s:' , 'plugin-name' ), $tax_fields['single'] ),
'search_items' => sprintf( __( 'Search %s' , 'plugin-name' ), $tax_fields['plural'] ),
'popular_items' => sprintf( __( 'Popular %s' , 'plugin-name' ), $tax_fields['plural'] ),
'separate_items_with_commas' => sprintf( __( 'Separate %s with commas' , 'plugin-name' ), $tax_fields['plural'] ),
'add_or_remove_items' => sprintf( __( 'Add or remove %s' , 'plugin-name' ), $tax_fields['plural'] ),
'choose_from_most_used' => sprintf( __( 'Choose from the most used %s' , 'plugin-name' ), $tax_fields['plural'] ),
'not_found' => sprintf( __( 'No %s found' , 'plugin-name' ), $tax_fields['plural'] ),
);
$args = array(
'label' => $tax_fields['plural'],
'labels' => $labels,
'hierarchical' => ( isset( $tax_fields['hierarchical'] ) ) ? $tax_fields['hierarchical'] : true,
'public' => ( isset( $tax_fields['public'] ) ) ? $tax_fields['public'] : true,
'show_ui' => ( isset( $tax_fields['show_ui'] ) ) ? $tax_fields['show_ui'] : true,
'show_in_nav_menus' => ( isset( $tax_fields['show_in_nav_menus'] ) ) ? $tax_fields['show_in_nav_menus'] : true,
'show_tagcloud' => ( isset( $tax_fields['show_tagcloud'] ) ) ? $tax_fields['show_tagcloud'] : true,
'meta_box_cb' => ( isset( $tax_fields['meta_box_cb'] ) ) ? $tax_fields['meta_box_cb'] : null,
'show_admin_column' => ( isset( $tax_fields['show_admin_column'] ) ) ? $tax_fields['show_admin_column'] : true,
'show_in_quick_edit' => ( isset( $tax_fields['show_in_quick_edit'] ) ) ? $tax_fields['show_in_quick_edit'] : true,
'update_count_callback' => ( isset( $tax_fields['update_count_callback'] ) ) ? $tax_fields['update_count_callback'] : '',
'show_in_rest' => ( isset( $tax_fields['show_in_rest'] ) ) ? $tax_fields['show_in_rest'] : true,
'rest_base' => $tax_fields['taxonomy'],
'rest_controller_class' => ( isset( $tax_fields['rest_controller_class'] ) ) ? $tax_fields['rest_controller_class'] : 'WP_REST_Terms_Controller',
'query_var' => $tax_fields['taxonomy'],
'rewrite' => ( isset( $tax_fields['rewrite'] ) ) ? $tax_fields['rewrite'] : true,
'sort' => ( isset( $tax_fields['sort'] ) ) ? $tax_fields['sort'] : '',
);
$args = apply_filters( $tax_fields['taxonomy'] . '_args', $args );
register_taxonomy( $tax_fields['taxonomy'], $tax_fields['post_types'], $args );
}
/**
* Assign capabilities to users
*
* @link https://codex.wordpress.org/Function_Reference/register_post_type
* @link https://typerocket.com/ultimate-guide-to-custom-post-types-in-wordpress/
*/
public function assign_capabilities( $caps_map, $users ) {
foreach ( $users as $user ) {
$user_role = get_role( $user );
foreach ( $caps_map as $cap_map_key => $capability ) {
$user_role->add_cap( $capability );
}
}
}
/**
* CUSTOMIZE CUSTOM POST TYPE AS YOU WISH.
*/
/**
* Create post types
*/
public function create_custom_post_type() {
$food_menu_item_fields = array(
array(
'slug' => 'food-menu-item',
'singular' => 'Food Menu Item',
'plural' => 'Food Menu Items',
'menu_name' => 'Food Menu Items',
'description' => 'Food Menu Items',
'has_archive' => true,
'hierarchical' => false,
'menu_icon' => 'dashicons-carrot',
'rewrite' => array(
'slug' => 'food-menu-items',
'with_front' => true,
'pages' => true,
'feeds' => true,
'ep_mask' => EP_PERMALINK,
),
'menu_position' => 21,
'public' => true,
'publicly_queryable' => true,
'exclude_from_search' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'supports' => array(
'title',
'editor',
'excerpt',
'author',
'thumbnail',
'comments',
'trackbacks',
'custom-fields',
'revisions',
'page-attributes',
'post-formats',
),
'custom_caps' => true,
'custom_caps_users' => array(
'administrator',
),
'taxonomies' => array(
array(
'taxonomy' => 'food_menu_item_category',
'plural' => 'Food Menu Item Categories',
'single' => 'Food Menu Item Category',
'post_types' => array( 'Food Menu Item' ),
),
),
),
);
foreach ( $food_menu_item_fields as $fields ) {
$this->register_single_post_type( $fields );
}
// ...
}
// ...
}
?>
``` | The comments button and the share button are generated in two separate default actions, so you have to remove them both:
```
remove_action( 'embed_content_meta', 'print_embed_comments_button' );
remove_action( 'embed_content_meta', 'print_embed_sharing_button' );
``` |
355,741 | <p>I'm making a web app using wordpress, the app will include this <a href="https://github.com/pyrou/morpheus" rel="nofollow noreferrer">library</a> that will do some steganography operations. I need some help to understand how to implement a front-end image upload for the users that want to use the app, I've created a bs4 form that include a file upload input and a text area for the message to include inside the image and a second form that will process the images that contains hidden data. I need to upload the image, and then let the user download it before the system delete the image. Is this possible, how I manage the upload and download workflow in wp? </p>
| [
{
"answer_id": 355700,
"author": "Ahmedhere",
"author_id": 180546,
"author_profile": "https://wordpress.stackexchange.com/users/180546",
"pm_score": -1,
"selected": false,
"text": "<p>All the javascript files are embedded in the footer if you remove the footer maybe your site goes down. There are two ways:</p>\n\n<ol>\n<li>Create a child theme and create footer.php and call <code>wp_footer();</code> hook there.</li>\n<li>Or If you just want to remove the footer text you can do this in CSS just find the class or id and make it <code>display: none;</code></li>\n</ol>\n"
},
{
"answer_id": 402074,
"author": "Brett Donald",
"author_id": 143573,
"author_profile": "https://wordpress.stackexchange.com/users/143573",
"pm_score": 0,
"selected": false,
"text": "<p>The comments button and the share button are generated in two separate default actions, so you have to remove them both:</p>\n<pre><code>remove_action( 'embed_content_meta', 'print_embed_comments_button' );\nremove_action( 'embed_content_meta', 'print_embed_sharing_button' );\n</code></pre>\n"
}
] | 2020/01/05 | [
"https://wordpress.stackexchange.com/questions/355741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177581/"
] | I'm making a web app using wordpress, the app will include this [library](https://github.com/pyrou/morpheus) that will do some steganography operations. I need some help to understand how to implement a front-end image upload for the users that want to use the app, I've created a bs4 form that include a file upload input and a text area for the message to include inside the image and a second form that will process the images that contains hidden data. I need to upload the image, and then let the user download it before the system delete the image. Is this possible, how I manage the upload and download workflow in wp? | The comments button and the share button are generated in two separate default actions, so you have to remove them both:
```
remove_action( 'embed_content_meta', 'print_embed_comments_button' );
remove_action( 'embed_content_meta', 'print_embed_sharing_button' );
``` |
355,758 | <p>I'm a bit new to custom wordpress pages and I purchased a HTML theme that I successfully converted into a Wordpress site. The thing is, that there is a contact form that I would like to use and I've followed the codex instructions on using admin-post.php file but the form is not getting submitted. </p>
<p>Below is the form in my footer.php:</p>
<pre><code><form id="contact-form" method="POST" action="http://tvans.gr/wp-admin/admin-post.php">
<input type="hidden" name="action" value="send_form"/>
<input type="hidden" name="custom_nonce" value="<?php echo $custom_form_nonce ?>"/>
<input class="form-control form-text" id="name" type="text" name="name" value="" placeholder="Please Enter Name" required />
<input class="form-control form-text" id="email" type="email" name="email" value="" placeholder="Please Enter Email" required />
<textarea class="form-control form-text" id="message" name="message" placeholder="Message" rows="4" required></textarea>
<input type="submit" class="btn-1" id="submit" name="submit" value="SUBMIT">
<input type="reset" class="btn-1 distab-cell-middle cancel" name="clear" value="RESET">
</form>
</code></pre>
<p>And here is my functions.php file:</p>
<pre><code>function prefix_admin_send_form(){
echo $_POST['name'];
print($_POST['email']);
exit;
}
add_action('admin_post_send_form', 'prefix_admin_send_form');
</code></pre>
<p>The data in functions.php is for testing purposes but still I'm not getting any response. Is it something I did wrong here or is is something that I'm missing?
Thanks in advance for any help.</p>
| [
{
"answer_id": 355761,
"author": "Arturo Gallegos",
"author_id": 130585,
"author_profile": "https://wordpress.stackexchange.com/users/130585",
"pm_score": 1,
"selected": true,
"text": "<p>You can't use admin-post.php directly in your form, you need implement an ajax request.</p>\n\n<p><a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>To send your email have a function wp_mail\n<a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_mail/</a></p>\n\n<p>If you have problem to receive the POST params review this answer\n<a href=\"https://wordpress.stackexchange.com/questions/282163/wordpress-ajax-with-axios/284423#284423\">WordPress AJAX with Axios</a></p>\n"
},
{
"answer_id": 355765,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": -1,
"selected": false,
"text": "<p>You are using <code>admin_post</code> action, so you have to use <code>nopriv</code> action also if user is not logged in.\ncurrenly you are not getting any response beacuse user need to authenticated admin post action. nopriv is used to handle AJAX requests on the front-end for unauthenticated users.</p>\n\n<p><strong>Footer.php :</strong></p>\n\n<pre><code><form id=\"contact-form\" method=\"POST\" action=\"<?php echo admin_url( 'admin-post.php' ); ?>\">\n <input type=\"hidden\" name=\"action\" value=\"send_form\"/>\n <input type=\"hidden\" name=\"custom_nonce\" value=\"<?php echo $custom_form_nonce ?>\"/>\n\n <input class=\"form-control form-text\" id=\"name\" type=\"text\" name=\"name\" value=\"\" placeholder=\"Please Enter Name\" required />\n <input class=\"form-control form-text\" id=\"email\" type=\"email\" name=\"email\" value=\"\" placeholder=\"Please Enter Email\" required />\n <textarea class=\"form-control form-text\" id=\"message\" name=\"message\" placeholder=\"Message\" rows=\"4\" required></textarea>\n <input type=\"submit\" class=\"btn-1\" id=\"submit\" name=\"submit\" value=\"SUBMIT\">\n <input type=\"reset\" class=\"btn-1 distab-cell-middle cancel\" name=\"clear\" value=\"RESET\">\n</form>\n</code></pre>\n\n<p><strong>functions.php</strong></p>\n\n<pre><code>function prefix_admin_send_form(){\n echo $_POST['name'];\n print($_POST['email']);\n exit;\n}\n\nadd_action('admin_post_send_form', 'prefix_admin_send_form');\nadd_action('admin_post_nopriv_send_form', 'prefix_admin_send_form' ); // You nedd to this action\n</code></pre>\n"
}
] | 2020/01/06 | [
"https://wordpress.stackexchange.com/questions/355758",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180622/"
] | I'm a bit new to custom wordpress pages and I purchased a HTML theme that I successfully converted into a Wordpress site. The thing is, that there is a contact form that I would like to use and I've followed the codex instructions on using admin-post.php file but the form is not getting submitted.
Below is the form in my footer.php:
```
<form id="contact-form" method="POST" action="http://tvans.gr/wp-admin/admin-post.php">
<input type="hidden" name="action" value="send_form"/>
<input type="hidden" name="custom_nonce" value="<?php echo $custom_form_nonce ?>"/>
<input class="form-control form-text" id="name" type="text" name="name" value="" placeholder="Please Enter Name" required />
<input class="form-control form-text" id="email" type="email" name="email" value="" placeholder="Please Enter Email" required />
<textarea class="form-control form-text" id="message" name="message" placeholder="Message" rows="4" required></textarea>
<input type="submit" class="btn-1" id="submit" name="submit" value="SUBMIT">
<input type="reset" class="btn-1 distab-cell-middle cancel" name="clear" value="RESET">
</form>
```
And here is my functions.php file:
```
function prefix_admin_send_form(){
echo $_POST['name'];
print($_POST['email']);
exit;
}
add_action('admin_post_send_form', 'prefix_admin_send_form');
```
The data in functions.php is for testing purposes but still I'm not getting any response. Is it something I did wrong here or is is something that I'm missing?
Thanks in advance for any help. | You can't use admin-post.php directly in your form, you need implement an ajax request.
<https://codex.wordpress.org/AJAX_in_Plugins>
To send your email have a function wp\_mail
<https://developer.wordpress.org/reference/functions/wp_mail/>
If you have problem to receive the POST params review this answer
[WordPress AJAX with Axios](https://wordpress.stackexchange.com/questions/282163/wordpress-ajax-with-axios/284423#284423) |
355,840 | <p>I have translated the po file and uploaded the mo and po files in the languages folder with the language code file name. But translation is not loading
Here is the function file code:</p>
<pre><code>if( is_dir( get_stylesheet_directory() . '/languages' ) ) {
load_theme_textdomain('adifier', get_stylesheet_directory() . '/languages');
} else{
load_theme_textdomain('adifier', get_template_directory() . '/languages');
}
</code></pre>
<p><img src="https://i.stack.imgur.com/KMTDB.jpg" alt="enter image description here"></p>
| [
{
"answer_id": 355770,
"author": "artasena",
"author_id": 158909,
"author_profile": "https://wordpress.stackexchange.com/users/158909",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe u should switch using another builder, you can combine 2 plugin functionality with this :</p>\n\n<ol>\n<li>Elementor Pro (is your base/main plugin for builder).</li>\n<li>JetEngine by Crocoblock. (will be like an addon to make specific template with custom post type functionality and custom field).</li>\n</ol>\n\n<p>Personally i just switch to both of them from WP Bakery.</p>\n"
},
{
"answer_id": 358437,
"author": "MIGUEL ANGEL CANO QUIÑONEZ",
"author_id": 182573,
"author_profile": "https://wordpress.stackexchange.com/users/182573",
"pm_score": 2,
"selected": false,
"text": "<p>I was able to find a solution by doing a find and replace on this file</p>\n\n<p>/wp-content/plugins/js_composer/assets/js/dist/backend.min.js\n$.ajax -> jQuery.ajax</p>\n\n<p>Changing the $ symbol out to jQuery fixed the issue.</p>\n"
}
] | 2020/01/06 | [
"https://wordpress.stackexchange.com/questions/355840",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180664/"
] | I have translated the po file and uploaded the mo and po files in the languages folder with the language code file name. But translation is not loading
Here is the function file code:
```
if( is_dir( get_stylesheet_directory() . '/languages' ) ) {
load_theme_textdomain('adifier', get_stylesheet_directory() . '/languages');
} else{
load_theme_textdomain('adifier', get_template_directory() . '/languages');
}
```
 | I was able to find a solution by doing a find and replace on this file
/wp-content/plugins/js\_composer/assets/js/dist/backend.min.js
$.ajax -> jQuery.ajax
Changing the $ symbol out to jQuery fixed the issue. |
355,855 | <p>On my localhost environment the following code works perfect</p>
<pre><code> $creds['user_login'] = $user_login;
$creds['user_password'] = $user_password;
$user = wp_signon( $creds, true );
if(!is_wp_error($user)) {
wp_redirect('/home');
exit;
}
</code></pre>
<p>But on the server it doesn't work anymore. The user is never logged in.
The website is hosted on a https subdomain on an external server.</p>
<p>I tried setting a cookie domain in my wp-config:</p>
<pre><code>define('COOKIE_DOMAIN', '.domain.com');
</code></pre>
<p>And also with the subdomain included:</p>
<pre><code>define('COOKIE_DOMAIN', 'sub.domain.com');
</code></pre>
<p>Neither worked for me.</p>
<p>The server runs on PHP 7.1 with Varnish.
Swift Performance is used for caching.</p>
| [
{
"answer_id": 355770,
"author": "artasena",
"author_id": 158909,
"author_profile": "https://wordpress.stackexchange.com/users/158909",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe u should switch using another builder, you can combine 2 plugin functionality with this :</p>\n\n<ol>\n<li>Elementor Pro (is your base/main plugin for builder).</li>\n<li>JetEngine by Crocoblock. (will be like an addon to make specific template with custom post type functionality and custom field).</li>\n</ol>\n\n<p>Personally i just switch to both of them from WP Bakery.</p>\n"
},
{
"answer_id": 358437,
"author": "MIGUEL ANGEL CANO QUIÑONEZ",
"author_id": 182573,
"author_profile": "https://wordpress.stackexchange.com/users/182573",
"pm_score": 2,
"selected": false,
"text": "<p>I was able to find a solution by doing a find and replace on this file</p>\n\n<p>/wp-content/plugins/js_composer/assets/js/dist/backend.min.js\n$.ajax -> jQuery.ajax</p>\n\n<p>Changing the $ symbol out to jQuery fixed the issue.</p>\n"
}
] | 2020/01/07 | [
"https://wordpress.stackexchange.com/questions/355855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165616/"
] | On my localhost environment the following code works perfect
```
$creds['user_login'] = $user_login;
$creds['user_password'] = $user_password;
$user = wp_signon( $creds, true );
if(!is_wp_error($user)) {
wp_redirect('/home');
exit;
}
```
But on the server it doesn't work anymore. The user is never logged in.
The website is hosted on a https subdomain on an external server.
I tried setting a cookie domain in my wp-config:
```
define('COOKIE_DOMAIN', '.domain.com');
```
And also with the subdomain included:
```
define('COOKIE_DOMAIN', 'sub.domain.com');
```
Neither worked for me.
The server runs on PHP 7.1 with Varnish.
Swift Performance is used for caching. | I was able to find a solution by doing a find and replace on this file
/wp-content/plugins/js\_composer/assets/js/dist/backend.min.js
$.ajax -> jQuery.ajax
Changing the $ symbol out to jQuery fixed the issue. |
355,892 | <p>I need to sanitize some custom settings added with the Customize API, namely some simple text fields.</p>
<p>Other data types have some dedicated functions, i.e. email addresses should use <code>sanitize_email()</code>, URL's have <code>esc_url_raw()</code> and so on.</p>
<p>But with simple text fields, I'm not really sure if I must use <a href="https://developer.wordpress.org/reference/functions/sanitize_text_field/" rel="nofollow noreferrer"><code>sanitize_text_field()</code></a> or <a href="https://developer.wordpress.org/reference/functions/wp_filter_nohtml_kses/" rel="nofollow noreferrer"><code>wp_filter_nohtml_kses()</code></a>, even after reading their descriptions in the Code Reference they seem to be very similar and I don' really know how to choose one of them.</p>
<p>Intuitively, I would go with <code>sanitize_text_field()</code>, but some online guides (<a href="https://maddisondesigns.com/2017/05/the-wordpress-customizer-a-developers-guide-part-1/" rel="nofollow noreferrer">this</a> and <a href="https://divpusher.com/blog/wordpress-customizer-sanitization-examples/#text" rel="nofollow noreferrer">this</a>) seem to suggest that <code>wp_filter_nohtml_kses()</code> is what should be used instead.</p>
<p><strong>What are the exact differences between these two functions, and how can I choose one of them in this situation?</strong></p>
| [
{
"answer_id": 355897,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<h3>What Do They Do?</h3>\n<p><code>wp_filter_nohtml_kses</code> strips all HTML from a string, that's it. It does it via the <code>wp_kses</code> function and it expects slashed data, here's its implementation:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wp_filter_nohtml_kses( $data ) {\n return addslashes( wp_kses( stripslashes( $data ), 'strip' ) );\n}\n</code></pre>\n<p><code>sanitize_text_field</code> on the other hand does more than that, the doc says:</p>\n<blockquote>\n<ul>\n<li>Checks for invalid UTF-8,</li>\n<li>Converts single < characters to entities</li>\n<li>Strips all tags</li>\n<li>Removes line breaks, tabs, and extra whitespace</li>\n<li>Strips octets</li>\n</ul>\n</blockquote>\n<p>Specificially the point of <code>sanitize_text_field</code> is to sanitize text fields. Since you want to sanitize a text field, you should use <code>sanitize_text_field</code>.</p>\n<h3>So Why Does One Article Recommend <code>wp_filter_nohtml_kses</code>?</h3>\n<p><strong>It doesn't.</strong></p>\n<p>The author correctly recognised the variable may contain HTML, and searched for a function to do just that, and found <code>wp_filter_nohtml_kses</code>.</p>\n<p><em>However this is neither the best function for this job, or the appropriate one.</em> <code>sanitize_text_field</code> targets the actual problem, that the field needs sanitising, and does a more than strip out tags.</p>\n<p>The author could easily have chosen <code>wp_strip_all_tags</code>, but should have gone for <code>sanitize_text_field</code>.</p>\n<p>Which brings us to the main points:</p>\n<ol>\n<li>Not all guides are correct</li>\n<li>When faced with a choice between 2 functions, pick the one that literally says what you want to do, not the obscure one</li>\n<li><code>wp_filter_nohtml_kses</code> would not have protected against octal characters, and other things that <code>sanitize_text_field</code> does, but perhaps the author was unaware of those attack vectors?</li>\n<li>Some of the things <code>sanitize_text_field</code> does are less about security and more about cleanliness, e.g. stripping extra whitespace</li>\n</ol>\n<h3>Escaping vs Sanitising</h3>\n<blockquote>\n<p>URL's have esc_url_raw() and so on.</p>\n</blockquote>\n<p>Not quite, <code>esc_url_raw</code> is an escaping function, escaping is not sanitisation! Though this is a rare exception where it can be used as a sanitising function</p>\n<ul>\n<li>Sanitising data cleans it</li>\n<li>Validating data confirms it</li>\n<li>Escaping data secures it</li>\n</ul>\n<p>Sanitise and validate on input, escape on output.</p>\n<p>Another way to think of it, is like a gameshow:</p>\n<ul>\n<li>Sanitising is the cleanup they do to get you ready for TV</li>\n<li>Validation is the judge at the end of the round who checks that you did what you were asked</li>\n<li>Escaping is the giant wall with the shaped hole you have to fit through or it'll push you off the ledge</li>\n</ul>\n<p>For example, consider this value: <code>" [email protected] <b>hello!</b> "</code></p>\n<ul>\n<li>we sanitize with <code>sanitize_email</code>, eliminating trailing spaces, etc, giving us <code>[email protected]</code></li>\n<li>we can validate it with <code>validate_email</code> to check if it is indeed an email</li>\n<li>At this point we can process the input</li>\n</ul>\n<p>Some time passes...</p>\n<ul>\n<li>now we need to output the data, so we escape it</li>\n<li><code>echo esc_url( 'mailto:'.$email );</code></li>\n</ul>\n<p>Now we get a <code>mailto</code> link with an email, <strong>it will always be a link</strong>. There is no dithering about it should be a link, it can be a link, it's supposed to be a link, etc. It is guaranteed to be a link, there is now certainty. No assumptions need to be made.</p>\n<p>Lets say that <code>$email</code> was sanitised and validated, and saved, yet the sites database was mangled or modified during a hack. Now, <code>$email</code> contains a JS bitcoin miner! Or it did until <code>esc_url</code> mangled it into an email. The email isn't usable, but it has the format of an email.</p>\n<p>For this reason, escaping is only done on output, uses an escaping function appropriate for the exected output, not the data ( <code>esc_attr</code> for html attributes, <code>esc_html</code> for text, <code>esc_url</code> for URLs, and so on ). Escaping is also done at the latest possible moment, closest to output. This way escaped data can't be modified after its been escaped, and there's no confusion about when something was escaped that might cause double escaping.</p>\n<p>For this reason, avoid adding HTML to a variable then echoing it at the end, or passing around complex HTML fragments in variables. You have no way to know if they're safe or not</p>\n"
},
{
"answer_id": 355898,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>The key difference is <code>sanitize_text_field()</code>:</p>\n\n<ul>\n<li>Checks for invalid UTF-8</li>\n<li>Converts single <code><</code> characters to entities</li>\n<li>Strips all tags</li>\n<li>Removes line breaks, tabs, and extra whitespace</li>\n<li>Strips octets</li>\n</ul>\n\n<p>...and is designed primarily for user input (e.g. <code>GET/POST/COOKIE</code>).</p>\n\n<p>Meanwhile <code>wp_filter_nohtml_kses()</code> <em>just</em> strips all HTML from a text string. Worth noting that it expects the string param you pass <a href=\"https://make.wordpress.org/core/2016/04/06/rest-api-slashed-data-in-wordpress-4-4-and-4-5/\" rel=\"nofollow noreferrer\">to be slashed</a>.</p>\n\n<p>As for which one you use, tradition says \"sanitize on input, escape on output\". Which would suggest <code>sanitize_text_field</code> in your case, and use <code>wp_filter_nohtml_kses</code> (or similar) when you output it.</p>\n\n<p>Having said that, if you never want users to be able to save HTML in these text fields, you should strip it out on input too - but <em>always</em> use <code>sanitize_text_field</code> (or similar) beforehand.</p>\n"
}
] | 2020/01/07 | [
"https://wordpress.stackexchange.com/questions/355892",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98169/"
] | I need to sanitize some custom settings added with the Customize API, namely some simple text fields.
Other data types have some dedicated functions, i.e. email addresses should use `sanitize_email()`, URL's have `esc_url_raw()` and so on.
But with simple text fields, I'm not really sure if I must use [`sanitize_text_field()`](https://developer.wordpress.org/reference/functions/sanitize_text_field/) or [`wp_filter_nohtml_kses()`](https://developer.wordpress.org/reference/functions/wp_filter_nohtml_kses/), even after reading their descriptions in the Code Reference they seem to be very similar and I don' really know how to choose one of them.
Intuitively, I would go with `sanitize_text_field()`, but some online guides ([this](https://maddisondesigns.com/2017/05/the-wordpress-customizer-a-developers-guide-part-1/) and [this](https://divpusher.com/blog/wordpress-customizer-sanitization-examples/#text)) seem to suggest that `wp_filter_nohtml_kses()` is what should be used instead.
**What are the exact differences between these two functions, and how can I choose one of them in this situation?** | ### What Do They Do?
`wp_filter_nohtml_kses` strips all HTML from a string, that's it. It does it via the `wp_kses` function and it expects slashed data, here's its implementation:
```php
function wp_filter_nohtml_kses( $data ) {
return addslashes( wp_kses( stripslashes( $data ), 'strip' ) );
}
```
`sanitize_text_field` on the other hand does more than that, the doc says:
>
> * Checks for invalid UTF-8,
> * Converts single < characters to entities
> * Strips all tags
> * Removes line breaks, tabs, and extra whitespace
> * Strips octets
>
>
>
Specificially the point of `sanitize_text_field` is to sanitize text fields. Since you want to sanitize a text field, you should use `sanitize_text_field`.
### So Why Does One Article Recommend `wp_filter_nohtml_kses`?
**It doesn't.**
The author correctly recognised the variable may contain HTML, and searched for a function to do just that, and found `wp_filter_nohtml_kses`.
*However this is neither the best function for this job, or the appropriate one.* `sanitize_text_field` targets the actual problem, that the field needs sanitising, and does a more than strip out tags.
The author could easily have chosen `wp_strip_all_tags`, but should have gone for `sanitize_text_field`.
Which brings us to the main points:
1. Not all guides are correct
2. When faced with a choice between 2 functions, pick the one that literally says what you want to do, not the obscure one
3. `wp_filter_nohtml_kses` would not have protected against octal characters, and other things that `sanitize_text_field` does, but perhaps the author was unaware of those attack vectors?
4. Some of the things `sanitize_text_field` does are less about security and more about cleanliness, e.g. stripping extra whitespace
### Escaping vs Sanitising
>
> URL's have esc\_url\_raw() and so on.
>
>
>
Not quite, `esc_url_raw` is an escaping function, escaping is not sanitisation! Though this is a rare exception where it can be used as a sanitising function
* Sanitising data cleans it
* Validating data confirms it
* Escaping data secures it
Sanitise and validate on input, escape on output.
Another way to think of it, is like a gameshow:
* Sanitising is the cleanup they do to get you ready for TV
* Validation is the judge at the end of the round who checks that you did what you were asked
* Escaping is the giant wall with the shaped hole you have to fit through or it'll push you off the ledge
For example, consider this value: `" [email protected] <b>hello!</b> "`
* we sanitize with `sanitize_email`, eliminating trailing spaces, etc, giving us `[email protected]`
* we can validate it with `validate_email` to check if it is indeed an email
* At this point we can process the input
Some time passes...
* now we need to output the data, so we escape it
* `echo esc_url( 'mailto:'.$email );`
Now we get a `mailto` link with an email, **it will always be a link**. There is no dithering about it should be a link, it can be a link, it's supposed to be a link, etc. It is guaranteed to be a link, there is now certainty. No assumptions need to be made.
Lets say that `$email` was sanitised and validated, and saved, yet the sites database was mangled or modified during a hack. Now, `$email` contains a JS bitcoin miner! Or it did until `esc_url` mangled it into an email. The email isn't usable, but it has the format of an email.
For this reason, escaping is only done on output, uses an escaping function appropriate for the exected output, not the data ( `esc_attr` for html attributes, `esc_html` for text, `esc_url` for URLs, and so on ). Escaping is also done at the latest possible moment, closest to output. This way escaped data can't be modified after its been escaped, and there's no confusion about when something was escaped that might cause double escaping.
For this reason, avoid adding HTML to a variable then echoing it at the end, or passing around complex HTML fragments in variables. You have no way to know if they're safe or not |
355,968 | <p>I would like to extend the default image block and add an option to it.</p>
<p><a href="https://i.stack.imgur.com/Ognqq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ognqq.png" alt="enter image description here"></a></p>
<p>The idea is to have an extra option to download the image locally if it is a remote image.</p>
<p>Is this possible and how ?
Thanks.</p>
| [
{
"answer_id": 356118,
"author": "gordie",
"author_id": 70449,
"author_profile": "https://wordpress.stackexchange.com/users/70449",
"pm_score": -1,
"selected": false,
"text": "<p>I found this tutorial, <a href=\"https://neliosoftware.com/blog/how-to-add-button-gutenberg-blocks/\" rel=\"nofollow noreferrer\">How to Add a Button to The Gutenberg Editor</a>, and <a href=\"https://github.com/avillegasn/nelio-gutenberg-custom-button\" rel=\"nofollow noreferrer\">its example on Github</a>.</p>\n"
},
{
"answer_id": 398663,
"author": "Mat Lipe",
"author_id": 129914,
"author_profile": "https://wordpress.stackexchange.com/users/129914",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress provides a <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blockedit\" rel=\"nofollow noreferrer\">JS filter</a> for adjusting the components used with the <code>edit</code> state called <code>editor.BlockEdit</code>. Passing a callback to said filter with a <code>BlockControls</code> <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/block-controls-toolbar-and-sidebar/#block-toolbar\" rel=\"nofollow noreferrer\">fill</a> allows you to inject whatever components you need.</p>\n<p>The components returned from your callback will show up on every block by default. You can limit the return to your targeted block(s) by using the name of the block which is passed as <code>name</code> to the callback.</p>\n<p>Putting it all together.</p>\n<pre><code>import {addFilter} from '@wordpress/hooks';\nimport {BlockControls} from '@wordpress/block-editor';\nimport {ToolbarButton} from '@wordpress/components';\n\n\nconst Download = BlockEdit => {\n return props => {\n if ( props.name !== 'core/image' ) {\n return <BlockEdit {...props} />;\n }\n\n return (\n <>\n <BlockControls>\n <ToolbarButton\n icon={'download'}\n label="Download"\n onClick={() => alert( props.attributes?.url )}\n />\n </BlockControls>\n <BlockEdit {...props} />\n </>\n );\n };\n};\n\n\naddFilter( 'editor.BlockEdit', 'your-namespace', Download );\n</code></pre>\n<p>If you need custom attributes because you are saving data to the block you are extending, you may use the <code>blocks.registerBlockType</code> <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype\" rel=\"nofollow noreferrer\">filter</a>.</p>\n<p>Assuming you are adding a custom <code>downloadFile</code> attribute, it could look like this.</p>\n<pre><code>function addAttribute( settings ) {\n if ( settings.name !== 'core/table' ) {\n return settings;\n }\n\n settings.attributes = {\n ...settings.attributes,\n downloadFile: {\n type: 'string',\n },\n };\n return settings;\n}\n\naddFilter( 'blocks.registerBlockType', 'your-namespace', addAttribute );\n</code></pre>\n<p>You can set the value of the attribute using <code>setAttributes</code> which is passed to your callback above.</p>\n<pre><code><ToolbarButton\n icon={'download'}\n label="Download"\n onClick={() => props.setAttribute( {\n downloadFile: 'this is the new value',\n } )}\n/>\n</code></pre>\n"
},
{
"answer_id": 409551,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 1,
"selected": false,
"text": "<p>While the slotfill might not be available in WP >= 5.9 any more (I didn't check that) as @mat-lipe mentioned in <a href=\"https://wordpress.stackexchange.com/a/398663/47733\">his answer</a> there is another approach that should work for any block:</p>\n<p>Using the <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blockedit\" rel=\"nofollow noreferrer\">editor.BlockEdit filter</a> you can add a <a href=\"https://developer.wordpress.org/block-editor/reference-guides/components/toolbar-button/#inside-blockcontrols\" rel=\"nofollow noreferrer\"><code><ToolbarButton></code></a> to a block.</p>\n"
}
] | 2020/01/08 | [
"https://wordpress.stackexchange.com/questions/355968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70449/"
] | I would like to extend the default image block and add an option to it.
[](https://i.stack.imgur.com/Ognqq.png)
The idea is to have an extra option to download the image locally if it is a remote image.
Is this possible and how ?
Thanks. | WordPress provides a [JS filter](https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blockedit) for adjusting the components used with the `edit` state called `editor.BlockEdit`. Passing a callback to said filter with a `BlockControls` [fill](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/block-controls-toolbar-and-sidebar/#block-toolbar) allows you to inject whatever components you need.
The components returned from your callback will show up on every block by default. You can limit the return to your targeted block(s) by using the name of the block which is passed as `name` to the callback.
Putting it all together.
```
import {addFilter} from '@wordpress/hooks';
import {BlockControls} from '@wordpress/block-editor';
import {ToolbarButton} from '@wordpress/components';
const Download = BlockEdit => {
return props => {
if ( props.name !== 'core/image' ) {
return <BlockEdit {...props} />;
}
return (
<>
<BlockControls>
<ToolbarButton
icon={'download'}
label="Download"
onClick={() => alert( props.attributes?.url )}
/>
</BlockControls>
<BlockEdit {...props} />
</>
);
};
};
addFilter( 'editor.BlockEdit', 'your-namespace', Download );
```
If you need custom attributes because you are saving data to the block you are extending, you may use the `blocks.registerBlockType` [filter](https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype).
Assuming you are adding a custom `downloadFile` attribute, it could look like this.
```
function addAttribute( settings ) {
if ( settings.name !== 'core/table' ) {
return settings;
}
settings.attributes = {
...settings.attributes,
downloadFile: {
type: 'string',
},
};
return settings;
}
addFilter( 'blocks.registerBlockType', 'your-namespace', addAttribute );
```
You can set the value of the attribute using `setAttributes` which is passed to your callback above.
```
<ToolbarButton
icon={'download'}
label="Download"
onClick={() => props.setAttribute( {
downloadFile: 'this is the new value',
} )}
/>
``` |
356,005 | <p>I have this table that is generated in a Custom Post Type (CPT)</p>
<p><a href="https://i.stack.imgur.com/NXga8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NXga8.png" alt="enter image description here"></a></p>
<p>Is there an option that I can modify the query? For example, I have this post_type = 'my-type' in wp_posts table. I want to do a JOIN to have specific values with the table wp_postmeta - how can I do that? Where do I edit the query?</p>
<p>I want to list only posts that have an specific value in its meta, for that I need to do a join, all of this is to have control in what an specific user can see</p>
| [
{
"answer_id": 356118,
"author": "gordie",
"author_id": 70449,
"author_profile": "https://wordpress.stackexchange.com/users/70449",
"pm_score": -1,
"selected": false,
"text": "<p>I found this tutorial, <a href=\"https://neliosoftware.com/blog/how-to-add-button-gutenberg-blocks/\" rel=\"nofollow noreferrer\">How to Add a Button to The Gutenberg Editor</a>, and <a href=\"https://github.com/avillegasn/nelio-gutenberg-custom-button\" rel=\"nofollow noreferrer\">its example on Github</a>.</p>\n"
},
{
"answer_id": 398663,
"author": "Mat Lipe",
"author_id": 129914,
"author_profile": "https://wordpress.stackexchange.com/users/129914",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress provides a <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blockedit\" rel=\"nofollow noreferrer\">JS filter</a> for adjusting the components used with the <code>edit</code> state called <code>editor.BlockEdit</code>. Passing a callback to said filter with a <code>BlockControls</code> <a href=\"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/block-controls-toolbar-and-sidebar/#block-toolbar\" rel=\"nofollow noreferrer\">fill</a> allows you to inject whatever components you need.</p>\n<p>The components returned from your callback will show up on every block by default. You can limit the return to your targeted block(s) by using the name of the block which is passed as <code>name</code> to the callback.</p>\n<p>Putting it all together.</p>\n<pre><code>import {addFilter} from '@wordpress/hooks';\nimport {BlockControls} from '@wordpress/block-editor';\nimport {ToolbarButton} from '@wordpress/components';\n\n\nconst Download = BlockEdit => {\n return props => {\n if ( props.name !== 'core/image' ) {\n return <BlockEdit {...props} />;\n }\n\n return (\n <>\n <BlockControls>\n <ToolbarButton\n icon={'download'}\n label="Download"\n onClick={() => alert( props.attributes?.url )}\n />\n </BlockControls>\n <BlockEdit {...props} />\n </>\n );\n };\n};\n\n\naddFilter( 'editor.BlockEdit', 'your-namespace', Download );\n</code></pre>\n<p>If you need custom attributes because you are saving data to the block you are extending, you may use the <code>blocks.registerBlockType</code> <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype\" rel=\"nofollow noreferrer\">filter</a>.</p>\n<p>Assuming you are adding a custom <code>downloadFile</code> attribute, it could look like this.</p>\n<pre><code>function addAttribute( settings ) {\n if ( settings.name !== 'core/table' ) {\n return settings;\n }\n\n settings.attributes = {\n ...settings.attributes,\n downloadFile: {\n type: 'string',\n },\n };\n return settings;\n}\n\naddFilter( 'blocks.registerBlockType', 'your-namespace', addAttribute );\n</code></pre>\n<p>You can set the value of the attribute using <code>setAttributes</code> which is passed to your callback above.</p>\n<pre><code><ToolbarButton\n icon={'download'}\n label="Download"\n onClick={() => props.setAttribute( {\n downloadFile: 'this is the new value',\n } )}\n/>\n</code></pre>\n"
},
{
"answer_id": 409551,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 1,
"selected": false,
"text": "<p>While the slotfill might not be available in WP >= 5.9 any more (I didn't check that) as @mat-lipe mentioned in <a href=\"https://wordpress.stackexchange.com/a/398663/47733\">his answer</a> there is another approach that should work for any block:</p>\n<p>Using the <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blockedit\" rel=\"nofollow noreferrer\">editor.BlockEdit filter</a> you can add a <a href=\"https://developer.wordpress.org/block-editor/reference-guides/components/toolbar-button/#inside-blockcontrols\" rel=\"nofollow noreferrer\"><code><ToolbarButton></code></a> to a block.</p>\n"
}
] | 2020/01/09 | [
"https://wordpress.stackexchange.com/questions/356005",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180791/"
] | I have this table that is generated in a Custom Post Type (CPT)
[](https://i.stack.imgur.com/NXga8.png)
Is there an option that I can modify the query? For example, I have this post\_type = 'my-type' in wp\_posts table. I want to do a JOIN to have specific values with the table wp\_postmeta - how can I do that? Where do I edit the query?
I want to list only posts that have an specific value in its meta, for that I need to do a join, all of this is to have control in what an specific user can see | WordPress provides a [JS filter](https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blockedit) for adjusting the components used with the `edit` state called `editor.BlockEdit`. Passing a callback to said filter with a `BlockControls` [fill](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/block-controls-toolbar-and-sidebar/#block-toolbar) allows you to inject whatever components you need.
The components returned from your callback will show up on every block by default. You can limit the return to your targeted block(s) by using the name of the block which is passed as `name` to the callback.
Putting it all together.
```
import {addFilter} from '@wordpress/hooks';
import {BlockControls} from '@wordpress/block-editor';
import {ToolbarButton} from '@wordpress/components';
const Download = BlockEdit => {
return props => {
if ( props.name !== 'core/image' ) {
return <BlockEdit {...props} />;
}
return (
<>
<BlockControls>
<ToolbarButton
icon={'download'}
label="Download"
onClick={() => alert( props.attributes?.url )}
/>
</BlockControls>
<BlockEdit {...props} />
</>
);
};
};
addFilter( 'editor.BlockEdit', 'your-namespace', Download );
```
If you need custom attributes because you are saving data to the block you are extending, you may use the `blocks.registerBlockType` [filter](https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype).
Assuming you are adding a custom `downloadFile` attribute, it could look like this.
```
function addAttribute( settings ) {
if ( settings.name !== 'core/table' ) {
return settings;
}
settings.attributes = {
...settings.attributes,
downloadFile: {
type: 'string',
},
};
return settings;
}
addFilter( 'blocks.registerBlockType', 'your-namespace', addAttribute );
```
You can set the value of the attribute using `setAttributes` which is passed to your callback above.
```
<ToolbarButton
icon={'download'}
label="Download"
onClick={() => props.setAttribute( {
downloadFile: 'this is the new value',
} )}
/>
``` |
356,106 | <p>I know that there is already a <a href="https://wordpress.stackexchange.com/questions/263924/wordpress-localhost-site-redirect-to-live-site">similar question</a> like this. But I have already done all these suggested solution and nothing works for me.</p>
<ul>
<li><p>If there are caching plugins installed like W3 total cache. Then purge cache first. Or may be disable them for time being </p>
<ul>
<li>I have already disabled any possible plugin that using cache or redirection ]</li>
</ul></li>
<li><p>Perform Search and Replace in the database for Old Site URL. You can Use this Plugin . </p>
<ul>
<li>I opened sql file and perform search and replace for the live url into my local url ]</li>
</ul></li>
<li><p>Reset Permalinks ( Dashboard >> Settings >> Permalinks ). </p>
<ul>
<li>I used wp cli to perform permalinks reset ]</li>
</ul></li>
<li><p>Last but not the least. Clear your browser Cache and History </p>
<ul>
<li>Always clearing my browser and even using incognito ]</li>
</ul></li>
</ul>
<p>When I deleted all the existing tables, wordpress asking me to setup new wordpress but when I put the tables back, still redirecting me to the live site. Any suggestion? </p>
| [
{
"answer_id": 356131,
"author": "Captain S.",
"author_id": 106778,
"author_profile": "https://wordpress.stackexchange.com/users/106778",
"pm_score": 0,
"selected": false,
"text": "<p>check your wp-config.php if you have defined 'WP_HOME' and/or 'WP_SITEURL'. Setting these values will override the wp_options table values. If that doesn't help I recommend the tool <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">database search and replace</a>.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 356140,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>Look in your <code>wp_options</code> database table for the <code>siteurl</code> and <code>home</code> options and check these are using your local URL.</p>\n\n<p>As Captain S commented, these can also be overridden in your wp-config:</p>\n\n<pre><code>define('WP_HOME', 'http://www.localsite.test');\ndefine('WP_SITEURL', 'http://www.localsite.test');\n</code></pre>\n"
},
{
"answer_id": 356197,
"author": "bryanxkier",
"author_id": 180585,
"author_profile": "https://wordpress.stackexchange.com/users/180585",
"pm_score": 0,
"selected": false,
"text": "<p>Solved. Someone put a redirection code on the theme itself</p>\n"
}
] | 2020/01/10 | [
"https://wordpress.stackexchange.com/questions/356106",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180585/"
] | I know that there is already a [similar question](https://wordpress.stackexchange.com/questions/263924/wordpress-localhost-site-redirect-to-live-site) like this. But I have already done all these suggested solution and nothing works for me.
* If there are caching plugins installed like W3 total cache. Then purge cache first. Or may be disable them for time being
+ I have already disabled any possible plugin that using cache or redirection ]
* Perform Search and Replace in the database for Old Site URL. You can Use this Plugin .
+ I opened sql file and perform search and replace for the live url into my local url ]
* Reset Permalinks ( Dashboard >> Settings >> Permalinks ).
+ I used wp cli to perform permalinks reset ]
* Last but not the least. Clear your browser Cache and History
+ Always clearing my browser and even using incognito ]
When I deleted all the existing tables, wordpress asking me to setup new wordpress but when I put the tables back, still redirecting me to the live site. Any suggestion? | Look in your `wp_options` database table for the `siteurl` and `home` options and check these are using your local URL.
As Captain S commented, these can also be overridden in your wp-config:
```
define('WP_HOME', 'http://www.localsite.test');
define('WP_SITEURL', 'http://www.localsite.test');
``` |
356,126 | <p>I want to display user's locations which they travelled on author box so how can I add this kind of input area to users profile? To more explain, If a user add <code>"Londra,Paris"</code> to own profile, these cities will seem author box as a tag.Londra and Paris must be entered to different areas so users can add extra fields. If it is impossible, how can I divide cities which form of <code>"Paris,Londra"</code> to use in city tags. I talk about divide all words by <code>,</code>. I hope I could explain me.</p>
<p>Or explode lines like Hello Kity,
and the function counts how many is there location</p>
| [
{
"answer_id": 356131,
"author": "Captain S.",
"author_id": 106778,
"author_profile": "https://wordpress.stackexchange.com/users/106778",
"pm_score": 0,
"selected": false,
"text": "<p>check your wp-config.php if you have defined 'WP_HOME' and/or 'WP_SITEURL'. Setting these values will override the wp_options table values. If that doesn't help I recommend the tool <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">database search and replace</a>.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 356140,
"author": "Alexander Holsgrove",
"author_id": 48962,
"author_profile": "https://wordpress.stackexchange.com/users/48962",
"pm_score": 1,
"selected": false,
"text": "<p>Look in your <code>wp_options</code> database table for the <code>siteurl</code> and <code>home</code> options and check these are using your local URL.</p>\n\n<p>As Captain S commented, these can also be overridden in your wp-config:</p>\n\n<pre><code>define('WP_HOME', 'http://www.localsite.test');\ndefine('WP_SITEURL', 'http://www.localsite.test');\n</code></pre>\n"
},
{
"answer_id": 356197,
"author": "bryanxkier",
"author_id": 180585,
"author_profile": "https://wordpress.stackexchange.com/users/180585",
"pm_score": 0,
"selected": false,
"text": "<p>Solved. Someone put a redirection code on the theme itself</p>\n"
}
] | 2020/01/10 | [
"https://wordpress.stackexchange.com/questions/356126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180894/"
] | I want to display user's locations which they travelled on author box so how can I add this kind of input area to users profile? To more explain, If a user add `"Londra,Paris"` to own profile, these cities will seem author box as a tag.Londra and Paris must be entered to different areas so users can add extra fields. If it is impossible, how can I divide cities which form of `"Paris,Londra"` to use in city tags. I talk about divide all words by `,`. I hope I could explain me.
Or explode lines like Hello Kity,
and the function counts how many is there location | Look in your `wp_options` database table for the `siteurl` and `home` options and check these are using your local URL.
As Captain S commented, these can also be overridden in your wp-config:
```
define('WP_HOME', 'http://www.localsite.test');
define('WP_SITEURL', 'http://www.localsite.test');
``` |
356,147 | <p>I am new here, I do not have a ton of experience with PHP but if I have a correct block I can work the different functions. I have a static page, currently, I have it set to display 5 snippets of posts, we have a ton of them on this category, and I need this page to have a line of links with</p>
<p>Newest 1, 2, 3, ... Oldest ... </p>
<p>I cannot get it to display that...</p>
<p>My current code looks like this:</p>
<pre><code> <?php while ( have_posts() ) : the_post(); ?>
<div class="title text-center">
<h1><strong><?php the_title();?></strong></h1>
<img src="<?php echo get_template_directory_uri(); ?>/images/title.png" title="title-line" alt="title-line">
</div>
<div id="no-more-tables" class="legel">
<?php the_content();?></div>
<?php
$posts = get_posts(array(
'posts_per_page' => 5,
'category'=>'13'
));
if( $posts ): ?>
<div>
<?php foreach( $posts as $post ):
setup_postdata( $post );
?>
</code></pre>
<p>What do I need to add in order to make it do that? I am looking at this example, but it is not making sense to me:</p>
<pre><code><?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php __('No News'); ?></p>
<?php endif; ?>
</code></pre>
<p>I would appreciate any suggestions you may have...</p>
| [
{
"answer_id": 356144,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on your goal, you can add custom CSS for blocks in several ways.</p>\n\n<p><strong>Theme</strong></p>\n\n<p>Adding it \"themewide\" by either using a theme's Custom CSS area or creating a child theme could be used either to affect all copies of a particular type of block, or to target one type of block on just a single post. For example, each URL of a WP site should have a <body> class that specifies what type of content it is, and this gets fairly granular. Example: if there's one Page you want to target, <code>body.page-id-#</code> targets that page, so you can isolate your CSS to only affect that Page. This is the most common way to apply block style changes, because as you mentioned everywhere you use that class, you can update it once in the theme and it affects all those places simultaneously.</p>\n\n<p><strong>Plugin</strong></p>\n\n<p>You could also write a plugin to enqueue CSS only in the places you need it. That could vary: you could enqueue it on all Pages, or on Categories, or on a single Post, whatever you need.</p>\n\n<p>Or, if your theme doesn't have a Custom CSS area, there are out-of-the-box plugins that will allow you to add your own CSS. You'd have to look into their capabilities to see whether it's possible to restrict the CSS to certain areas, or if it's like a theme change, sitewide.</p>\n\n<p><strong>Inline</strong></p>\n\n<p>Finally, you have identified the only option that would allow you to add inline CSS - using the HTML block. WP shies away from inline styles in most cases because of its modularity - typically if you change something in one place, it's convenient to have it automatically update everywhere else, which classes do. Inline styles have to be updated individually.</p>\n"
},
{
"answer_id": 356153,
"author": "Krishan Kaushik",
"author_id": 175251,
"author_profile": "https://wordpress.stackexchange.com/users/175251",
"pm_score": 0,
"selected": false,
"text": "<p><strong>add code in your functions.php</strong></p>\n\n<pre><code>\nadd_action('wp_head', 'hook_in_frontend_head');\n\nfunction hook_in_frontend_head() {\n$screen = get_current_screen();\n\nif($screen->id == 'your-blog-page-id') {\n?> <style> your additionl styles here</style>\n<?php\n}\n\n}\n</code></pre>\n"
}
] | 2020/01/10 | [
"https://wordpress.stackexchange.com/questions/356147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180902/"
] | I am new here, I do not have a ton of experience with PHP but if I have a correct block I can work the different functions. I have a static page, currently, I have it set to display 5 snippets of posts, we have a ton of them on this category, and I need this page to have a line of links with
Newest 1, 2, 3, ... Oldest ...
I cannot get it to display that...
My current code looks like this:
```
<?php while ( have_posts() ) : the_post(); ?>
<div class="title text-center">
<h1><strong><?php the_title();?></strong></h1>
<img src="<?php echo get_template_directory_uri(); ?>/images/title.png" title="title-line" alt="title-line">
</div>
<div id="no-more-tables" class="legel">
<?php the_content();?></div>
<?php
$posts = get_posts(array(
'posts_per_page' => 5,
'category'=>'13'
));
if( $posts ): ?>
<div>
<?php foreach( $posts as $post ):
setup_postdata( $post );
?>
```
What do I need to add in order to make it do that? I am looking at this example, but it is not making sense to me:
```
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php __('No News'); ?></p>
<?php endif; ?>
```
I would appreciate any suggestions you may have... | Depending on your goal, you can add custom CSS for blocks in several ways.
**Theme**
Adding it "themewide" by either using a theme's Custom CSS area or creating a child theme could be used either to affect all copies of a particular type of block, or to target one type of block on just a single post. For example, each URL of a WP site should have a <body> class that specifies what type of content it is, and this gets fairly granular. Example: if there's one Page you want to target, `body.page-id-#` targets that page, so you can isolate your CSS to only affect that Page. This is the most common way to apply block style changes, because as you mentioned everywhere you use that class, you can update it once in the theme and it affects all those places simultaneously.
**Plugin**
You could also write a plugin to enqueue CSS only in the places you need it. That could vary: you could enqueue it on all Pages, or on Categories, or on a single Post, whatever you need.
Or, if your theme doesn't have a Custom CSS area, there are out-of-the-box plugins that will allow you to add your own CSS. You'd have to look into their capabilities to see whether it's possible to restrict the CSS to certain areas, or if it's like a theme change, sitewide.
**Inline**
Finally, you have identified the only option that would allow you to add inline CSS - using the HTML block. WP shies away from inline styles in most cases because of its modularity - typically if you change something in one place, it's convenient to have it automatically update everywhere else, which classes do. Inline styles have to be updated individually. |
356,154 | <p>good day dear community,</p>
<p>after having nailed down several issues with the set up of the theme twentyseventeen - the question today is: wordpress-theme 2017: featured image behaviour: where to set the height of the featured image!? </p>
<p>Well while i was doing a little google-search i have found the following;
I have been searching on the whole net in order to find something useful for the solution that i can apply various (different) on the WordPress-twentyseventeen-theme:</p>
<p>Well what is wanted and what is needed: I have found a way to resize the so called featured image of the theme because its way too big. On post pages when you put a featured image its a perfect size on all devices, but when I try to put featured image on a regular page its way to big as well.</p>
<p>see the page: <a href="http://www.job-starter.com/" rel="nofollow noreferrer">http://www.job-starter.com/</a> - a truely beta-beta-page that only serves as a demo. </p>
<p>see the images that are way too big: The questions are the following ones:</p>
<p>– how can I adjust the size so I can make like a header for the different pages, lets say i take the following size: 800 x 175
– can i do this by pasting this little text-chunk at the end of the css – in the so called css-file:</p>
<p>i have this following code in the theme-customizer - "additional CSS"</p>
<p>question: what do i need to change - in order to make the featured image smaller!?</p>
<p>see the code:</p>
<pre><code>.wrap { max-width: 1366px; }
.wrap { max-width: 1366px; }
/*For Content*/
.has-sidebar:not(.error404) #primary {
width: 60%
}
/*For Sidebar*/
.has-sidebar #secondary {
width: 30%
}
/*Responsive*/
@media(max-width:768px) {
/*For Content*/
.has-sidebar:not(.error404) #primary {
width: 100%
}
/*For Sidebar*/
.has-sidebar #secondary {
width: 100%
}
}
/* STRUCTURE */
.wrap {
max-width: 80% !important;
}
.page.page-one-column:not(.twentyseventeen-front-page) #primary {
max-width: 100% !important;
}
@media screen and (min-width: 48em) {
.wrap {
max-width: 80% !important;
}
}
@media screen and (min-width: 30em) {
.page-one-column .panel-content .wrap {
max-width: 80% !important;
}
}
@media screen and (max-width: 650px) {
.wrap {
max-width: 95% !important;
}
}
</code></pre>
<p>for any and all help i thank you - all help will be greatly appreciated</p>
| [
{
"answer_id": 356144,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on your goal, you can add custom CSS for blocks in several ways.</p>\n\n<p><strong>Theme</strong></p>\n\n<p>Adding it \"themewide\" by either using a theme's Custom CSS area or creating a child theme could be used either to affect all copies of a particular type of block, or to target one type of block on just a single post. For example, each URL of a WP site should have a <body> class that specifies what type of content it is, and this gets fairly granular. Example: if there's one Page you want to target, <code>body.page-id-#</code> targets that page, so you can isolate your CSS to only affect that Page. This is the most common way to apply block style changes, because as you mentioned everywhere you use that class, you can update it once in the theme and it affects all those places simultaneously.</p>\n\n<p><strong>Plugin</strong></p>\n\n<p>You could also write a plugin to enqueue CSS only in the places you need it. That could vary: you could enqueue it on all Pages, or on Categories, or on a single Post, whatever you need.</p>\n\n<p>Or, if your theme doesn't have a Custom CSS area, there are out-of-the-box plugins that will allow you to add your own CSS. You'd have to look into their capabilities to see whether it's possible to restrict the CSS to certain areas, or if it's like a theme change, sitewide.</p>\n\n<p><strong>Inline</strong></p>\n\n<p>Finally, you have identified the only option that would allow you to add inline CSS - using the HTML block. WP shies away from inline styles in most cases because of its modularity - typically if you change something in one place, it's convenient to have it automatically update everywhere else, which classes do. Inline styles have to be updated individually.</p>\n"
},
{
"answer_id": 356153,
"author": "Krishan Kaushik",
"author_id": 175251,
"author_profile": "https://wordpress.stackexchange.com/users/175251",
"pm_score": 0,
"selected": false,
"text": "<p><strong>add code in your functions.php</strong></p>\n\n<pre><code>\nadd_action('wp_head', 'hook_in_frontend_head');\n\nfunction hook_in_frontend_head() {\n$screen = get_current_screen();\n\nif($screen->id == 'your-blog-page-id') {\n?> <style> your additionl styles here</style>\n<?php\n}\n\n}\n</code></pre>\n"
}
] | 2020/01/11 | [
"https://wordpress.stackexchange.com/questions/356154",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177513/"
] | good day dear community,
after having nailed down several issues with the set up of the theme twentyseventeen - the question today is: wordpress-theme 2017: featured image behaviour: where to set the height of the featured image!?
Well while i was doing a little google-search i have found the following;
I have been searching on the whole net in order to find something useful for the solution that i can apply various (different) on the WordPress-twentyseventeen-theme:
Well what is wanted and what is needed: I have found a way to resize the so called featured image of the theme because its way too big. On post pages when you put a featured image its a perfect size on all devices, but when I try to put featured image on a regular page its way to big as well.
see the page: <http://www.job-starter.com/> - a truely beta-beta-page that only serves as a demo.
see the images that are way too big: The questions are the following ones:
– how can I adjust the size so I can make like a header for the different pages, lets say i take the following size: 800 x 175
– can i do this by pasting this little text-chunk at the end of the css – in the so called css-file:
i have this following code in the theme-customizer - "additional CSS"
question: what do i need to change - in order to make the featured image smaller!?
see the code:
```
.wrap { max-width: 1366px; }
.wrap { max-width: 1366px; }
/*For Content*/
.has-sidebar:not(.error404) #primary {
width: 60%
}
/*For Sidebar*/
.has-sidebar #secondary {
width: 30%
}
/*Responsive*/
@media(max-width:768px) {
/*For Content*/
.has-sidebar:not(.error404) #primary {
width: 100%
}
/*For Sidebar*/
.has-sidebar #secondary {
width: 100%
}
}
/* STRUCTURE */
.wrap {
max-width: 80% !important;
}
.page.page-one-column:not(.twentyseventeen-front-page) #primary {
max-width: 100% !important;
}
@media screen and (min-width: 48em) {
.wrap {
max-width: 80% !important;
}
}
@media screen and (min-width: 30em) {
.page-one-column .panel-content .wrap {
max-width: 80% !important;
}
}
@media screen and (max-width: 650px) {
.wrap {
max-width: 95% !important;
}
}
```
for any and all help i thank you - all help will be greatly appreciated | Depending on your goal, you can add custom CSS for blocks in several ways.
**Theme**
Adding it "themewide" by either using a theme's Custom CSS area or creating a child theme could be used either to affect all copies of a particular type of block, or to target one type of block on just a single post. For example, each URL of a WP site should have a <body> class that specifies what type of content it is, and this gets fairly granular. Example: if there's one Page you want to target, `body.page-id-#` targets that page, so you can isolate your CSS to only affect that Page. This is the most common way to apply block style changes, because as you mentioned everywhere you use that class, you can update it once in the theme and it affects all those places simultaneously.
**Plugin**
You could also write a plugin to enqueue CSS only in the places you need it. That could vary: you could enqueue it on all Pages, or on Categories, or on a single Post, whatever you need.
Or, if your theme doesn't have a Custom CSS area, there are out-of-the-box plugins that will allow you to add your own CSS. You'd have to look into their capabilities to see whether it's possible to restrict the CSS to certain areas, or if it's like a theme change, sitewide.
**Inline**
Finally, you have identified the only option that would allow you to add inline CSS - using the HTML block. WP shies away from inline styles in most cases because of its modularity - typically if you change something in one place, it's convenient to have it automatically update everywhere else, which classes do. Inline styles have to be updated individually. |
356,160 | <p>I am using regular expression to get the text inside a single p tag targeting its class. the problem is I want to use a php variable as class name and use a loop to change the class name each time. </p>
<pre class="lang-php prettyprint-override"><code>$sample = get_the_content();
<button class="accordion">
preg_match('/<strong class="1">(.*?)<\/strong>/s', $sample, $match);
echo $match[1];
$className = "1";
</code></pre>
<p>I want to use the $classname varialbe up there and increment it in a loop to get different paragraph content each time.</p>
<p>I hope I am clear in my question.</p>
| [
{
"answer_id": 356165,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 1,
"selected": false,
"text": "<p>Note: this question is not related to WordPress, but rather to PHP directly and should be asked at <a href=\"https://stackoverflow.com/\">StackOverflow</a> but I have provided a very basic answer below to help you on your way. However be aware that this answer <strong>is not necessarily the best way</strong> to go about solving your problem, <strong>nor is it meant to be efficient</strong>.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// assuming get_the_content() equates to ↓\n\n$content = '<p class=\"1\">P1 Content</p><p class=\"2\">P2 Content</p><p class=\"3\">P3 Content</p>';\n\n$classNames = ['1', '2', '3'];\n\n$matches = [];\n\nforeach( $classNames as $className ) {\n\n $pattern = sprintf('\\<p\\sclass=\\\"%s\\\"\\>(.*?)\\<\\/p\\>', $className);\n\n preg_match(\"/{$pattern}/i\", $content, $found); \n\n $matches[] = $found;\n\n}\n\nvar_dump($matches);\n\n/*\narray(3) {\n [0]=>\n array(2) {\n [0]=>\n string(27) \"<p class=\"1\">P1 Content</p>\"\n [1]=>\n string(10) \"P1 Content\"\n }\n [1]=>\n array(2) {\n [0]=>\n string(27) \"<p class=\"2\">P2 Content</p>\"\n [1]=>\n string(10) \"P2 Content\"\n }\n [2]=>\n array(2) {\n [0]=>\n string(27) \"<p class=\"3\">P3 Content</p>\"\n [1]=>\n string(10) \"P3 Content\"\n }\n}\n*/\n\n</code></pre>\n\n<h2>UPDATE 1:</h2>\n\n<p>If you do not have a fixed, known-list (ahead of time) of class names, then use the following example which utilises <code>preg_match_all</code> and looks for any <code><P></code> tag with <code>class = NUMBER</code>.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><p class=\"1\">Content</p>\n<p class=\"2\">Content</p>\n<!-- etc.. -->\n<p class=\"234\">Content</p>\n</code></pre>\n\n<pre class=\"lang-php prettyprint-override\"><code>$content = '<p class=\"1\">P1 Content</p><p class=\"2\">P2 Content</p><p class=\"3\">P3 Content</p>';\n\n$pattern = sprintf('\\<p\\sclass=\\\"%s\\\"\\>(.*?)\\<\\/p\\>', '[0-9]+');\n\nvar_dump($pattern);\n\npreg_match_all(\"/{$pattern}/i\", $content, $found);\n\nvar_dump($found);\n\n/*\narray(2) {\n [0]=>\n array(3) {\n [0]=>\n string(27) \"<p class=\"1\">P1 Content</p>\"\n [1]=>\n string(27) \"<p class=\"2\">P2 Content</p>\"\n [2]=>\n string(27) \"<p class=\"3\">P3 Content</p>\"\n }\n [1]=>\n array(3) {\n [0]=>\n string(10) \"P1 Content\"\n [1]=>\n string(10) \"P2 Content\"\n [2]=>\n string(10) \"P3 Content\"\n }\n}\n*/\n</code></pre>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Iterate over the results (if any) and do something with the content.\n */\nif ( is_array($found) && isset($found[1]) ) {\n\n foreach( $found[1] as $content ) {\n\n echo $content;\n\n }\n\n}\n</code></pre>\n\n<p>Results in:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>P1 Content\nP2 Content\nP3 Content\n</code></pre>\n\n<p>I advise that you prefix your class names such as:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><p class=\"myprefix-1\">Content</p>\n<p class=\"myprefix-2\">Content</p>\n<!-- etc.. -->\n<p class=\"myprefix-234\">Content</p>\n</code></pre>\n\n<p>If so, make sure to update your regex pattern:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$pattern = sprintf('\\<p\\sclass=\\\"myprefix-%s\\\"\\>(.*?)\\<\\/p\\>', '[0-9]+');\n</code></pre>\n\n<h3><a href=\"https://repl.it/@fundemental/WPSE356165\" rel=\"nofollow noreferrer\">REPL.IT DEMO</a></h3>\n"
},
{
"answer_id": 356171,
"author": "Ashur",
"author_id": 180578,
"author_profile": "https://wordpress.stackexchange.com/users/180578",
"pm_score": 0,
"selected": false,
"text": "<p>I found a solution for my question and I like to share it:</p>\n\n<p>for this I simply created a php variable and added that in the middle of the parameter:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$sample = get_the_content(); \n\n$classes = '1';\n<button class=\"accordion\">\npreg_match('/<p class=\"'.$classes.'\">(.*?)<\\/p>/s', $sample, $match); \necho $match[1];\n</code></pre>\n\n<p>I am still confused how to increment the class by 1 to get different content each time.</p>\n"
},
{
"answer_id": 356173,
"author": "Ashur",
"author_id": 180578,
"author_profile": "https://wordpress.stackexchange.com/users/180578",
"pm_score": 0,
"selected": false,
"text": "<p>Dear \"Adam\" this is what I am trying to do but I have issue in the length of array.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$tkey = 'post-update';\n\n$update = new WP_Query(array(\n 'posts_per_page' => -1,\n 'tag' => $tkey\n));\n\nwp_reset_postdata();\n\nif ($update->have_posts()) {\n while ($update->have_posts()) {\n $update->the_post();\n $sample = get_the_content();\n }\n}\n\n$classes = array();\narray_push($classes, $match);\n\nforeach ($classes as $names => $text) {\n\n?>\n <button class=\"accordion\">\n <?php\n preg_match('/<strong class=\"' . $text . '\">(.*?)<\\/strong>/s', $sample, $match);\n echo $match[1];\n ?>\n </button>\n <div class=\"panel\">\n <p>\n <?php\n preg_match('/<p class=\"' . $text . '\">(.*?)<\\/p>/s', $sample, $match);\n echo $match[1];\n ?>\n </p>\n </div>\n<?php } ?>\n</div>\n</code></pre>\n"
}
] | 2020/01/11 | [
"https://wordpress.stackexchange.com/questions/356160",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180578/"
] | I am using regular expression to get the text inside a single p tag targeting its class. the problem is I want to use a php variable as class name and use a loop to change the class name each time.
```php
$sample = get_the_content();
<button class="accordion">
preg_match('/<strong class="1">(.*?)<\/strong>/s', $sample, $match);
echo $match[1];
$className = "1";
```
I want to use the $classname varialbe up there and increment it in a loop to get different paragraph content each time.
I hope I am clear in my question. | Note: this question is not related to WordPress, but rather to PHP directly and should be asked at [StackOverflow](https://stackoverflow.com/) but I have provided a very basic answer below to help you on your way. However be aware that this answer **is not necessarily the best way** to go about solving your problem, **nor is it meant to be efficient**.
```php
// assuming get_the_content() equates to ↓
$content = '<p class="1">P1 Content</p><p class="2">P2 Content</p><p class="3">P3 Content</p>';
$classNames = ['1', '2', '3'];
$matches = [];
foreach( $classNames as $className ) {
$pattern = sprintf('\<p\sclass=\"%s\"\>(.*?)\<\/p\>', $className);
preg_match("/{$pattern}/i", $content, $found);
$matches[] = $found;
}
var_dump($matches);
/*
array(3) {
[0]=>
array(2) {
[0]=>
string(27) "<p class="1">P1 Content</p>"
[1]=>
string(10) "P1 Content"
}
[1]=>
array(2) {
[0]=>
string(27) "<p class="2">P2 Content</p>"
[1]=>
string(10) "P2 Content"
}
[2]=>
array(2) {
[0]=>
string(27) "<p class="3">P3 Content</p>"
[1]=>
string(10) "P3 Content"
}
}
*/
```
UPDATE 1:
---------
If you do not have a fixed, known-list (ahead of time) of class names, then use the following example which utilises `preg_match_all` and looks for any `<P>` tag with `class = NUMBER`.
```html
<p class="1">Content</p>
<p class="2">Content</p>
<!-- etc.. -->
<p class="234">Content</p>
```
```php
$content = '<p class="1">P1 Content</p><p class="2">P2 Content</p><p class="3">P3 Content</p>';
$pattern = sprintf('\<p\sclass=\"%s\"\>(.*?)\<\/p\>', '[0-9]+');
var_dump($pattern);
preg_match_all("/{$pattern}/i", $content, $found);
var_dump($found);
/*
array(2) {
[0]=>
array(3) {
[0]=>
string(27) "<p class="1">P1 Content</p>"
[1]=>
string(27) "<p class="2">P2 Content</p>"
[2]=>
string(27) "<p class="3">P3 Content</p>"
}
[1]=>
array(3) {
[0]=>
string(10) "P1 Content"
[1]=>
string(10) "P2 Content"
[2]=>
string(10) "P3 Content"
}
}
*/
```
```php
/**
* Iterate over the results (if any) and do something with the content.
*/
if ( is_array($found) && isset($found[1]) ) {
foreach( $found[1] as $content ) {
echo $content;
}
}
```
Results in:
```html
P1 Content
P2 Content
P3 Content
```
I advise that you prefix your class names such as:
```html
<p class="myprefix-1">Content</p>
<p class="myprefix-2">Content</p>
<!-- etc.. -->
<p class="myprefix-234">Content</p>
```
If so, make sure to update your regex pattern:
```php
$pattern = sprintf('\<p\sclass=\"myprefix-%s\"\>(.*?)\<\/p\>', '[0-9]+');
```
### [REPL.IT DEMO](https://repl.it/@fundemental/WPSE356165) |
356,243 | <p>I'm creating my first Wordpress plugin. It's goal is to update information from admin user about the book stock using sku only.</p>
<p>There are 2 forms in update-stock.php page. First form takes sku input and retrieves stock info.
Second form takes the new stock value from the admin user.The page works fine if I submit it on the same page,but i want to simply it.</p>
<p>I don't know how to split and work with php files seamlessly on backend only.</p>
<p>When I tried changing the action attribute to a php file in a sub folder inside my plugin, it works but it does not retain the admin Dashboard but instead takes me to the frontend of the website.</p>
<p>I really want to know how to work with php files in plugin subfolders whilst stay in the backend only.</p>
<p>I have searched a lot online but there seems to be no proper guideline for Wordpress plugin development about how to handles other php files.</p>
<p>Any help or reference will be appreciated. </p>
<p>plugin-name.php</p>
<pre><code>define("PLUGIN_DIR_PATH",plugin_dir_path(__FILE__));
add_action( 'admin_menu', 'wim_register_my_custom_menu_page' );
function wim_register_my_custom_menu_page() {
add_menu_page(
__( 'Plugin name', 'textdomain' ),
'Plugin name',
'manage_options',
'plugin-name/plugin-name.php',
'plugin_name_pagefunc',
'dashicons-tickets',
6
);
add_submenu_page(
'plugin-name/plugin-name.php',
'Update Stock',
'Update Product',
'manage_options',
'update-stock',
'update_stockfunc',
'dashicons-welcome-add-page'
);
}
function plugin_name_pagefunc()
{
?>
<h1>Plugin Name</h1>
<h3>Thank you for installing our plugin.</h3>
<p>This plugin is under development. This plugin is being developed for learning plugin development.</p>
<?php
}
function update_stockfunc(){
include_once PLUGIN_DIR_PATH."/inc/views/update-stock.php";
}
?>
</code></pre>
<p>update-stock.php</p>
<pre><code><div class="wrap">
<h2>Update Stock</h2>
<form method="POST" >
<input type="number" name="skuInput" onmouseover="this.focus();" maxlength="13">
<button value="Submit" onclick="Submit" >Check Stock</button>
</form>
<hr>
<?php
$sku = $_POST['skuInput'];
$product_id = get_product_id_by_sku($sku);
$stock = get_stock_by_product_id($product_id);
function get_product_id_by_sku( $sku = false ) {
global $wpdb;
if( !$sku )
return null;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
if ( $product_id )
return $product_id;
return null;
}
function get_stock_by_product_id( $product_id = false ) {
global $wpdb;
if( !$product_id )
return null;
$stock = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->postmeta WHERE post_id='%s' and meta_key='_stock'",$product_id));
if ( $stock )
return $stock;
return null;
}
?>
<form method="POST" action="<?php echo plugins_url( 'update-stock-success.php', __FILE__ ); ?>">
<input name="updatedStock" type="number" value ="<?php echo
$stock;?>">
<input type="hidden" name="product_id2" value="<?php echo
$product_id ?>"/>
<button value="Submit" onclick="Submit" >Update Stock</button>
</form>
</code></pre>
<p>update-stock-success.php</p>
<pre><code><div class="wrap">
<h2>Product Stock was updated successfully</h2>
<?php
$updatedStock = $_POST['updatedStock'];
$product_id2 = $_POST['product_id2'];
echo "New updated stock is ".$updatedStock." has post
id".$product_id2;
update_post_meta( $post, '_stock', $updatedStock);
echo "New updated stock is ".$updatedStock." has post
id".$product_id2;
?>
</div>
</code></pre>
<p>The output goes to frontend as you can see in the image below:
<a href="https://i.stack.imgur.com/GUWoR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GUWoR.png" alt="update-stock-success.php is taken to the wordpress frontend"></a></p>
| [
{
"answer_id": 356184,
"author": "Younes.D",
"author_id": 65465,
"author_profile": "https://wordpress.stackexchange.com/users/65465",
"pm_score": -1,
"selected": false,
"text": "<p>it depends on what you want to do.\nfor example, suppose your plugin needs javascript for it to work. in this case, we can enqueue the javascript in the constructor of the Class : </p>\n\n<pre><code>class My_Plugin{\n\n function __construct (){\n\n add_action( 'wp_enqueue_scripts', array( $this , 'my_script' ) );\n\n }\n\n function my_script(){\n\n // here you use the wp_enqueue_script( );\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 356206,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>No, constructors should not define hooks. </p>\n\n<p>Constructors should be used to set the initial state of the object. Hooks have nothing to do with the object's initial state, so they don't belong in the constructor. Constructors should not have \"side effects\", so that using <code>new ClassName()</code> does not affect any other parts of the program, which is what registering hooks does.</p>\n\n<p>A good overview of this issue is <a href=\"https://tommcfarlin.com/wordpress-plugin-constructors-hooks/\" rel=\"nofollow noreferrer\">this article</a> by Tom McFarlin. It also offers an alternative.</p>\n"
}
] | 2020/01/13 | [
"https://wordpress.stackexchange.com/questions/356243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137273/"
] | I'm creating my first Wordpress plugin. It's goal is to update information from admin user about the book stock using sku only.
There are 2 forms in update-stock.php page. First form takes sku input and retrieves stock info.
Second form takes the new stock value from the admin user.The page works fine if I submit it on the same page,but i want to simply it.
I don't know how to split and work with php files seamlessly on backend only.
When I tried changing the action attribute to a php file in a sub folder inside my plugin, it works but it does not retain the admin Dashboard but instead takes me to the frontend of the website.
I really want to know how to work with php files in plugin subfolders whilst stay in the backend only.
I have searched a lot online but there seems to be no proper guideline for Wordpress plugin development about how to handles other php files.
Any help or reference will be appreciated.
plugin-name.php
```
define("PLUGIN_DIR_PATH",plugin_dir_path(__FILE__));
add_action( 'admin_menu', 'wim_register_my_custom_menu_page' );
function wim_register_my_custom_menu_page() {
add_menu_page(
__( 'Plugin name', 'textdomain' ),
'Plugin name',
'manage_options',
'plugin-name/plugin-name.php',
'plugin_name_pagefunc',
'dashicons-tickets',
6
);
add_submenu_page(
'plugin-name/plugin-name.php',
'Update Stock',
'Update Product',
'manage_options',
'update-stock',
'update_stockfunc',
'dashicons-welcome-add-page'
);
}
function plugin_name_pagefunc()
{
?>
<h1>Plugin Name</h1>
<h3>Thank you for installing our plugin.</h3>
<p>This plugin is under development. This plugin is being developed for learning plugin development.</p>
<?php
}
function update_stockfunc(){
include_once PLUGIN_DIR_PATH."/inc/views/update-stock.php";
}
?>
```
update-stock.php
```
<div class="wrap">
<h2>Update Stock</h2>
<form method="POST" >
<input type="number" name="skuInput" onmouseover="this.focus();" maxlength="13">
<button value="Submit" onclick="Submit" >Check Stock</button>
</form>
<hr>
<?php
$sku = $_POST['skuInput'];
$product_id = get_product_id_by_sku($sku);
$stock = get_stock_by_product_id($product_id);
function get_product_id_by_sku( $sku = false ) {
global $wpdb;
if( !$sku )
return null;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
if ( $product_id )
return $product_id;
return null;
}
function get_stock_by_product_id( $product_id = false ) {
global $wpdb;
if( !$product_id )
return null;
$stock = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->postmeta WHERE post_id='%s' and meta_key='_stock'",$product_id));
if ( $stock )
return $stock;
return null;
}
?>
<form method="POST" action="<?php echo plugins_url( 'update-stock-success.php', __FILE__ ); ?>">
<input name="updatedStock" type="number" value ="<?php echo
$stock;?>">
<input type="hidden" name="product_id2" value="<?php echo
$product_id ?>"/>
<button value="Submit" onclick="Submit" >Update Stock</button>
</form>
```
update-stock-success.php
```
<div class="wrap">
<h2>Product Stock was updated successfully</h2>
<?php
$updatedStock = $_POST['updatedStock'];
$product_id2 = $_POST['product_id2'];
echo "New updated stock is ".$updatedStock." has post
id".$product_id2;
update_post_meta( $post, '_stock', $updatedStock);
echo "New updated stock is ".$updatedStock." has post
id".$product_id2;
?>
</div>
```
The output goes to frontend as you can see in the image below:
[](https://i.stack.imgur.com/GUWoR.png) | No, constructors should not define hooks.
Constructors should be used to set the initial state of the object. Hooks have nothing to do with the object's initial state, so they don't belong in the constructor. Constructors should not have "side effects", so that using `new ClassName()` does not affect any other parts of the program, which is what registering hooks does.
A good overview of this issue is [this article](https://tommcfarlin.com/wordpress-plugin-constructors-hooks/) by Tom McFarlin. It also offers an alternative. |
356,299 | <p>I'd like to ask some help for this code for my wordpress page. I would like to display just the current portfolio categories on a portfolio page. I used this code, but it shows all the portfolio categories from the '6' parent. Thank you!</p>
<pre><code><?php
$args = array(
'hierarchical' => 1,
'taxonomy' => 'portfolio_category',
'hide_empty' => 0,
'parent' => 6,
);
$categories = get_categories($args);
foreach($categories as $category) {
echo '<a href="' . get_category_link($category->cat_ID) . '" title="' . $category->name . '">' . $category->name . '</a><br>';
}
</code></pre>
<p>?></p>
| [
{
"answer_id": 356184,
"author": "Younes.D",
"author_id": 65465,
"author_profile": "https://wordpress.stackexchange.com/users/65465",
"pm_score": -1,
"selected": false,
"text": "<p>it depends on what you want to do.\nfor example, suppose your plugin needs javascript for it to work. in this case, we can enqueue the javascript in the constructor of the Class : </p>\n\n<pre><code>class My_Plugin{\n\n function __construct (){\n\n add_action( 'wp_enqueue_scripts', array( $this , 'my_script' ) );\n\n }\n\n function my_script(){\n\n // here you use the wp_enqueue_script( );\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 356206,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>No, constructors should not define hooks. </p>\n\n<p>Constructors should be used to set the initial state of the object. Hooks have nothing to do with the object's initial state, so they don't belong in the constructor. Constructors should not have \"side effects\", so that using <code>new ClassName()</code> does not affect any other parts of the program, which is what registering hooks does.</p>\n\n<p>A good overview of this issue is <a href=\"https://tommcfarlin.com/wordpress-plugin-constructors-hooks/\" rel=\"nofollow noreferrer\">this article</a> by Tom McFarlin. It also offers an alternative.</p>\n"
}
] | 2020/01/13 | [
"https://wordpress.stackexchange.com/questions/356299",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181003/"
] | I'd like to ask some help for this code for my wordpress page. I would like to display just the current portfolio categories on a portfolio page. I used this code, but it shows all the portfolio categories from the '6' parent. Thank you!
```
<?php
$args = array(
'hierarchical' => 1,
'taxonomy' => 'portfolio_category',
'hide_empty' => 0,
'parent' => 6,
);
$categories = get_categories($args);
foreach($categories as $category) {
echo '<a href="' . get_category_link($category->cat_ID) . '" title="' . $category->name . '">' . $category->name . '</a><br>';
}
```
?> | No, constructors should not define hooks.
Constructors should be used to set the initial state of the object. Hooks have nothing to do with the object's initial state, so they don't belong in the constructor. Constructors should not have "side effects", so that using `new ClassName()` does not affect any other parts of the program, which is what registering hooks does.
A good overview of this issue is [this article](https://tommcfarlin.com/wordpress-plugin-constructors-hooks/) by Tom McFarlin. It also offers an alternative. |
356,366 | <p>I have a post in category A that contain this redirection script:</p>
<pre><code><script>window.location.replace("http://www.w3schools.com");</script>
</code></pre>
<p>However, when I click on A, it also redirects. How to prevent this?</p>
| [
{
"answer_id": 356372,
"author": "Paul Elrich",
"author_id": 160341,
"author_profile": "https://wordpress.stackexchange.com/users/160341",
"pm_score": 2,
"selected": true,
"text": "<p>If that redirection script is written in the content section of the post, it is probably being called in with the rest of the content on the category page. </p>\n\n<p>You could add a URL check to your javascript that would look like this:</p>\n\n<pre><code>if(document.URL.indexOf(\"foo_page.html\") >= 0){ \n window.location.replace(\"http://www.w3schools.com\");\n}\n</code></pre>\n\n<p>And add in your permalink to the if statement</p>\n"
},
{
"answer_id": 356377,
"author": "KFish",
"author_id": 158938,
"author_profile": "https://wordpress.stackexchange.com/users/158938",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>A post has a js redirection script.</p>\n</blockquote>\n\n<p>Full Stop. If you're redirecting anything in JS, start from there as the first failure point. There's really no reason anything should be redirecting from JS on the front end. There are plenty of redirection plugins out there to handle any redirection rules you might need. Delete the script, redirect the page properly, and move on. </p>\n\n<p>There are of course ways to \"fix\" what you're trying to do, i.e. strip any scripts out of the post content before outputting it on the category pages, which you should be doing anyway. But you're still better off not having a redirect performed from the front end in JS.</p>\n"
}
] | 2020/01/14 | [
"https://wordpress.stackexchange.com/questions/356366",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64282/"
] | I have a post in category A that contain this redirection script:
```
<script>window.location.replace("http://www.w3schools.com");</script>
```
However, when I click on A, it also redirects. How to prevent this? | If that redirection script is written in the content section of the post, it is probably being called in with the rest of the content on the category page.
You could add a URL check to your javascript that would look like this:
```
if(document.URL.indexOf("foo_page.html") >= 0){
window.location.replace("http://www.w3schools.com");
}
```
And add in your permalink to the if statement |
356,418 | <p>I don't want to show all attributes that are available, I just need to show those variations value which have stock saved on back-end.
Just like I have a variable named sizes, so i want to show the product as well as its available sizes, if a product has 5 different sizes, but two of its sizes has no stock then display only the other 3 sizes which are in stock, and if one product has 5 different sizes and all sizes are in stock then display all those sizes. Here is the code that I am using:</p>
<pre><code> echo '<div class="row m-0 justify-content-center">';
$fabric_values = get_the_terms( $product->id, 'pa_sizes');
foreach ( $fabric_values as $fabric_value ) {
echo '<button class="btn btn-circle btn-lg rounded-circle">'."$fabric_value->name" . '</button>';
}
echo '</div>';
</code></pre>
<p>Here is the snap: <a href="https://i.stack.imgur.com/LSZ5f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LSZ5f.png" alt="See the image here"></a>
This shows all the attributes which I have stored before.
What's the solution, if anybody can help me?</p>
| [
{
"answer_id": 356372,
"author": "Paul Elrich",
"author_id": 160341,
"author_profile": "https://wordpress.stackexchange.com/users/160341",
"pm_score": 2,
"selected": true,
"text": "<p>If that redirection script is written in the content section of the post, it is probably being called in with the rest of the content on the category page. </p>\n\n<p>You could add a URL check to your javascript that would look like this:</p>\n\n<pre><code>if(document.URL.indexOf(\"foo_page.html\") >= 0){ \n window.location.replace(\"http://www.w3schools.com\");\n}\n</code></pre>\n\n<p>And add in your permalink to the if statement</p>\n"
},
{
"answer_id": 356377,
"author": "KFish",
"author_id": 158938,
"author_profile": "https://wordpress.stackexchange.com/users/158938",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>A post has a js redirection script.</p>\n</blockquote>\n\n<p>Full Stop. If you're redirecting anything in JS, start from there as the first failure point. There's really no reason anything should be redirecting from JS on the front end. There are plenty of redirection plugins out there to handle any redirection rules you might need. Delete the script, redirect the page properly, and move on. </p>\n\n<p>There are of course ways to \"fix\" what you're trying to do, i.e. strip any scripts out of the post content before outputting it on the category pages, which you should be doing anyway. But you're still better off not having a redirect performed from the front end in JS.</p>\n"
}
] | 2020/01/15 | [
"https://wordpress.stackexchange.com/questions/356418",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180889/"
] | I don't want to show all attributes that are available, I just need to show those variations value which have stock saved on back-end.
Just like I have a variable named sizes, so i want to show the product as well as its available sizes, if a product has 5 different sizes, but two of its sizes has no stock then display only the other 3 sizes which are in stock, and if one product has 5 different sizes and all sizes are in stock then display all those sizes. Here is the code that I am using:
```
echo '<div class="row m-0 justify-content-center">';
$fabric_values = get_the_terms( $product->id, 'pa_sizes');
foreach ( $fabric_values as $fabric_value ) {
echo '<button class="btn btn-circle btn-lg rounded-circle">'."$fabric_value->name" . '</button>';
}
echo '</div>';
```
Here is the snap: [](https://i.stack.imgur.com/LSZ5f.png)
This shows all the attributes which I have stored before.
What's the solution, if anybody can help me? | If that redirection script is written in the content section of the post, it is probably being called in with the rest of the content on the category page.
You could add a URL check to your javascript that would look like this:
```
if(document.URL.indexOf("foo_page.html") >= 0){
window.location.replace("http://www.w3schools.com");
}
```
And add in your permalink to the if statement |
356,419 | <p>I have page-property.php in the loop folder with this code. And I see only 8 posts (Custom Post type), but I want to see all of them with pagination, what's wrong?</p>
<pre><code><?php
$view = 'archive';
if ( is_singular() )
$view = 'single';
elseif ( is_search() )
$view = 'search';
elseif ( is_404() )
$view = '404';
if ( Pojo_Compatibility::is_bbpress_installed() && is_bbpress() )
$view = 'page';
do_action( 'pojo_setup_body_classes', $view, get_post_type(), '' );
get_header();
do_action( 'pojo_get_start_layout', $view, get_post_type(), '' );
?>
<header>
<?php if ( po_breadcrumbs_need_to_show() ) : ?>
<?php pojo_breadcrumbs(); ?>
<?php endif; ?>
<?php if ( pojo_is_show_page_title() ) : ?>
<div class="page-title">
<h1><?php the_title(); ?></h1>
</div>
<?php endif; ?>
</header>
<?php the_content(); ?>
<?php
global $_pojo_parent_id, $custom_query;
$_pojo_parent_id = get_the_ID();
$pagination = atmb_get_field( 'po_pagination' );
$display_type = po_get_display_type();
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array ( 'post_type' => 'property', 'post_per_page' => 8, 'paged' => $paged );
$custom_query = new WP_Query( $args );
?>
</code></pre>
<pre><code> <?php if ( $custom_query->have_posts() ) : ?>
<?php do_action( 'pojo_before_content_loop', $display_type ); ?>
<?php while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
<?php pojo_get_content_template_part( 'content', $display_type ); ?>
<?php endwhile;
?>
<?php do_action( 'pojo_after_content_loop', $display_type ); ?>
<?php if ( 'hide' !== $pagination ) : ?>
<?php pojo_paginate( ); ?>
<?php endif; ?>
<?php echo apply_filters( 'the_content', '' ); ?>
<?php endif; ?>
<?php endif; ?>
<?php pojo_button_post_edit(); ?>
</code></pre>
| [
{
"answer_id": 356434,
"author": "Waldo Rabie",
"author_id": 172667,
"author_profile": "https://wordpress.stackexchange.com/users/172667",
"pm_score": 0,
"selected": false,
"text": "<p>The problem could be a number of things. </p>\n\n<p>First of all, make sure you have more than 8 posts. If you do, then make sure you're pagination is working properly (numbered nav links to different pages should show up on page).</p>\n\n<p>Some more information would be helpful to better answer you question. Maybe a screenshot of the rendered page?</p>\n"
},
{
"answer_id": 356448,
"author": "Waldo Rabie",
"author_id": 172667,
"author_profile": "https://wordpress.stackexchange.com/users/172667",
"pm_score": 2,
"selected": true,
"text": "<p>If you go to the URL <a href=\"https://nadlancz.com/page/2/\" rel=\"nofollow noreferrer\">https://nadlancz.com/page/2/</a> you'll see that navigation works.</p>\n\n<p>What you need to do to see the navigation links is add something like this to your page </p>\n\n<pre><code><!-- Navigation -->\n<?php\n $pagination = get_the_posts_pagination(array(\n 'mid_size' => 2,\n 'prev_text' => 'Previous',\n 'next_text' => 'Next',\n ));\n\n if (defined('DOING_AJAX')) {\n $pagination = reformat_ajax_pagination($pagination);\n }\n\n echo $pagination;\n?>\n</code></pre>\n"
},
{
"answer_id": 356493,
"author": "studio josef office",
"author_id": 181105,
"author_profile": "https://wordpress.stackexchange.com/users/181105",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to all! I was needed to add parameter to <code>pojo_paginate()</code>:</p>\n\n<pre><code>pojo_paginate( $custom_query )\n</code></pre>\n"
}
] | 2020/01/15 | [
"https://wordpress.stackexchange.com/questions/356419",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181105/"
] | I have page-property.php in the loop folder with this code. And I see only 8 posts (Custom Post type), but I want to see all of them with pagination, what's wrong?
```
<?php
$view = 'archive';
if ( is_singular() )
$view = 'single';
elseif ( is_search() )
$view = 'search';
elseif ( is_404() )
$view = '404';
if ( Pojo_Compatibility::is_bbpress_installed() && is_bbpress() )
$view = 'page';
do_action( 'pojo_setup_body_classes', $view, get_post_type(), '' );
get_header();
do_action( 'pojo_get_start_layout', $view, get_post_type(), '' );
?>
<header>
<?php if ( po_breadcrumbs_need_to_show() ) : ?>
<?php pojo_breadcrumbs(); ?>
<?php endif; ?>
<?php if ( pojo_is_show_page_title() ) : ?>
<div class="page-title">
<h1><?php the_title(); ?></h1>
</div>
<?php endif; ?>
</header>
<?php the_content(); ?>
<?php
global $_pojo_parent_id, $custom_query;
$_pojo_parent_id = get_the_ID();
$pagination = atmb_get_field( 'po_pagination' );
$display_type = po_get_display_type();
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array ( 'post_type' => 'property', 'post_per_page' => 8, 'paged' => $paged );
$custom_query = new WP_Query( $args );
?>
```
```
<?php if ( $custom_query->have_posts() ) : ?>
<?php do_action( 'pojo_before_content_loop', $display_type ); ?>
<?php while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
<?php pojo_get_content_template_part( 'content', $display_type ); ?>
<?php endwhile;
?>
<?php do_action( 'pojo_after_content_loop', $display_type ); ?>
<?php if ( 'hide' !== $pagination ) : ?>
<?php pojo_paginate( ); ?>
<?php endif; ?>
<?php echo apply_filters( 'the_content', '' ); ?>
<?php endif; ?>
<?php endif; ?>
<?php pojo_button_post_edit(); ?>
``` | If you go to the URL <https://nadlancz.com/page/2/> you'll see that navigation works.
What you need to do to see the navigation links is add something like this to your page
```
<!-- Navigation -->
<?php
$pagination = get_the_posts_pagination(array(
'mid_size' => 2,
'prev_text' => 'Previous',
'next_text' => 'Next',
));
if (defined('DOING_AJAX')) {
$pagination = reformat_ajax_pagination($pagination);
}
echo $pagination;
?>
``` |
356,436 | <p>I do have a php website running on a certain domain, and I have installed Wordpress on a subdomain. I need to put a login form on the homepage (not the subdomain) where the user will fill in the username and password, then get logged in and redirected automatically to the Wordpress dashboard on the subdomain. But I'm a newbie, could anyone tell me how to achieve it? Thank you very much.</p>
| [
{
"answer_id": 356437,
"author": "Damocles",
"author_id": 180002,
"author_profile": "https://wordpress.stackexchange.com/users/180002",
"pm_score": 2,
"selected": false,
"text": "<p>You can add the static form code to your main site's code (your domain in this case is example.com and your subdomain is sub.example.com):</p>\n\n<pre><code><form name=\"loginform\" id=\"loginform\" action=\"https://sub.example.com/wp-login.php\" method=\"post\">\n <p>\n <label for=\"user_login\">Username or Email Address</label>\n <input type=\"text\" name=\"log\" id=\"user_login\" class=\"input\" value=\"\" size=\"20\" autocapitalize=\"off\">\n </p>\n\n <div class=\"user-pass-wrap\">\n <label for=\"user_pass\">Password</label>\n <div class=\"wp-pwd\">\n <input type=\"password\" name=\"pwd\" id=\"user_pass\" class=\"input password-input\" value=\"\" size=\"20\">\n <button type=\"button\" class=\"button button-secondary wp-hide-pw hide-if-no-js\" data-toggle=\"0\" aria-label=\"Show password\">\n <span class=\"dashicons dashicons-visibility\" aria-hidden=\"true\"></span>\n </button>\n </div>\n </div>\n <p class=\"forgetmenot\"><input name=\"rememberme\" type=\"checkbox\" id=\"rememberme\" value=\"forever\"> <label for=\"rememberme\">Remember Me</label></p>\n <p class=\"submit\">\n <input type=\"submit\" name=\"wp-submit\" id=\"wp-submit\" class=\"button button-primary button-large\" value=\"Log In\">\n <input type=\"hidden\" name=\"redirect_to\" value=\"https://sub.example.com/wp-admin/\">\n <input type=\"hidden\" name=\"testcookie\" value=\"1\">\n </p>\n </form>\n</code></pre>\n\n<p>The hidden redirect_to input field tells WP where it will redirect upon successful login (wp-admin/ will have you end up in the dashboard).</p>\n\n<p>The form however will not look like it does in WordPress due to the missing style. You can either add the WP <code>login.css</code> to your main site's code</p>\n\n<pre><code><link rel=\"stylesheet\" id=\"login-css\" href=\"https://sub.example.com/wp-admin/css/login.css?ver=5.3.2\" type=\"text/css\" media=\"all\">\n</code></pre>\n\n<p>or just style it the way you like.</p>\n"
},
{
"answer_id": 356438,
"author": "Tom",
"author_id": 3482,
"author_profile": "https://wordpress.stackexchange.com/users/3482",
"pm_score": -1,
"selected": false,
"text": "<p>There are several ways to achieve what you are looking for, but I am going to cover two in this answer:</p>\n\n<h2>WordPress, No Custom Coding (via Multisite)</h2>\n\n<p>A WordPress multisite gives you the ability to have two separate websites utilizing the same WordPress installation. You can set up your main domain (example.com) as the main multisite domain. Then, create a sub-site (or child site) that is your actual site (test.example.com). The subdomain site will contain your content.</p>\n\n<p>Lock both sites down by requiring login (<a href=\"https://wordpress.org/plugins/wp-force-login/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-force-login/</a>). Then set up the login page on the core site (example.com) and set a custom redirect after login to your subdomain (test.example.com). When the user logs in to one multisite site, they login across the network (this is also how WordPress.com works). So if they authenticate on the main site, the subsite is also logged in and you can redirect them there. </p>\n\n<p>On the subsite, require login and redirect them to the main site login page (example.com). That way, if they are no longer logged in but visit your subsite, they will be redirected to the login page. </p>\n\n<p>Additional reading: </p>\n\n<ul>\n<li><a href=\"https://wordpress.org/support/article/create-a-network/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/create-a-network/</a></li>\n<li><a href=\"https://kinsta.com/blog/wordpress-multisite/\" rel=\"nofollow noreferrer\">https://kinsta.com/blog/wordpress-multisite/</a></li>\n</ul>\n\n<h2>WordPress, Custom Code Method</h2>\n\n<p>WordPress has a way to authenticate users programatically. Utilizing the <code>wp_set_current_user()</code> and <code>wp_set_auth_cookie()</code> functions, you can authenticate a user via a PHP page on the main domain (example.com) and then redirect them to WordPress for authentication and processing. </p>\n\n<p>Additional reading: </p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/questions/53503/can-i-programmatically-login-a-user-without-a-password\">Can I programmatically login a user without a password?</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_set_auth_cookie/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_set_auth_cookie/</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_set_current_user\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_set_current_user</a></li>\n</ul>\n\n<p>Note: this method would require you to still authenticate the user without WordPress. I would recommend writing an API call that reaches out to WordPress and confirms the user credentials are authentic before redirecting them and \"auto-logging them in\" via the above functions. </p>\n"
}
] | 2020/01/15 | [
"https://wordpress.stackexchange.com/questions/356436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181118/"
] | I do have a php website running on a certain domain, and I have installed Wordpress on a subdomain. I need to put a login form on the homepage (not the subdomain) where the user will fill in the username and password, then get logged in and redirected automatically to the Wordpress dashboard on the subdomain. But I'm a newbie, could anyone tell me how to achieve it? Thank you very much. | You can add the static form code to your main site's code (your domain in this case is example.com and your subdomain is sub.example.com):
```
<form name="loginform" id="loginform" action="https://sub.example.com/wp-login.php" method="post">
<p>
<label for="user_login">Username or Email Address</label>
<input type="text" name="log" id="user_login" class="input" value="" size="20" autocapitalize="off">
</p>
<div class="user-pass-wrap">
<label for="user_pass">Password</label>
<div class="wp-pwd">
<input type="password" name="pwd" id="user_pass" class="input password-input" value="" size="20">
<button type="button" class="button button-secondary wp-hide-pw hide-if-no-js" data-toggle="0" aria-label="Show password">
<span class="dashicons dashicons-visibility" aria-hidden="true"></span>
</button>
</div>
</div>
<p class="forgetmenot"><input name="rememberme" type="checkbox" id="rememberme" value="forever"> <label for="rememberme">Remember Me</label></p>
<p class="submit">
<input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In">
<input type="hidden" name="redirect_to" value="https://sub.example.com/wp-admin/">
<input type="hidden" name="testcookie" value="1">
</p>
</form>
```
The hidden redirect\_to input field tells WP where it will redirect upon successful login (wp-admin/ will have you end up in the dashboard).
The form however will not look like it does in WordPress due to the missing style. You can either add the WP `login.css` to your main site's code
```
<link rel="stylesheet" id="login-css" href="https://sub.example.com/wp-admin/css/login.css?ver=5.3.2" type="text/css" media="all">
```
or just style it the way you like. |
356,443 | <p>I'm working on a new content type. Let's call it hotel rooms (it is not but the similarities are good enough).</p>
<p>Now, for each room, I will have a title and a description but I will also have a lot of metadata - beds, sea view, room number, size, summer price, winter price, and so on.</p>
<p>I would like my custom type to work on any theme. That means I need to provide a way to layout the post for <code>index.php</code>, <code>single.php</code>, and so forth. Obviously, presenting metadata is a large part of this.</p>
<p>How do I do this?</p>
| [
{
"answer_id": 356446,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 2,
"selected": false,
"text": "<p>I'd suggest to not add <em>layout</em>, but MarkUp and offer an option to override it. The best way to do this would be to add to a hook that your users can add to their themes templates.</p>\n\n<pre><code>// Theme template file\ndo_action( 'hotel_rooms' );\n\n// Your plugin hooks in there:\nadd_action( 'hotel_rooms', 'callback' );\nfunction callback() {\n echo \"I am displaying details about a hotel room\";\n}\n</code></pre>\n\n<p>You could also make this a two step process to offer more refined control:</p>\n\n<pre><code>// Themes template or another (child?) plugin\n// [] is an array and the default.\n$data = add_filter( 'hotel_room_data', [] );\n\n// Plugin\napply_filters( 'hotel_room_data', …etc. );\n</code></pre>\n\n<p><strong>Two stepped:</strong> Eat your own dog food and apply the filter to your own loops and MarkUp as well.</p>\n\n<pre><code>add_action( 'hotel_rooms', 'callback' );\nfunction callback() {\n $data = apply_filters( 'hotel_room_data', …etc. );\n foreach ( $data as $room ) {\n print $room['size'];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 356472,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 3,
"selected": true,
"text": "<p>I assume that you're making your custom post type in a plugin if you mean for it to work with any theme.</p>\n\n<p>In that case, I would suggest building your templates in your plugin, and call all your meta data there.</p>\n\n<p>Example:</p>\n\n<pre><code>/* Filter the single_template with our custom function*/\nadd_filter('single_template', 'my_custom_template');\n\nfunction my_custom_template($single) {\n\n global $post;\n\n /* Checks for single template by post type */\n if ( $post->post_type == 'POST TYPE NAME' ) {\n if ( file_exists( PLUGIN_PATH . '/Custom_File.php' ) ) {\n return PLUGIN_PATH . '/Custom_File.php';\n }\n }\n\n return $single;\n\n}\n</code></pre>\n\n<p>You can refine that further and add a function to check to see if the theme has single-yourposttype.php and to use that one if it exists instead of your plugin version, allowing for easy overrides by developers. Example:</p>\n\n<pre><code> $themeurl = get_theme_file_path(\"/single-yourposttype.php\");\n $pluginurl = plugin_dir_path( dirname( __FILE__ ) ) . 'single-yourposttype.php';\n\n if( file_exists( $themeurl ) ) {\n include( $themeurl );\n } elseif( file_exists( $pluginurl ) ) {\n\n require \"$pluginurl\";\n }\n</code></pre>\n\n<p>I hope that helps.</p>\n"
}
] | 2020/01/15 | [
"https://wordpress.stackexchange.com/questions/356443",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109240/"
] | I'm working on a new content type. Let's call it hotel rooms (it is not but the similarities are good enough).
Now, for each room, I will have a title and a description but I will also have a lot of metadata - beds, sea view, room number, size, summer price, winter price, and so on.
I would like my custom type to work on any theme. That means I need to provide a way to layout the post for `index.php`, `single.php`, and so forth. Obviously, presenting metadata is a large part of this.
How do I do this? | I assume that you're making your custom post type in a plugin if you mean for it to work with any theme.
In that case, I would suggest building your templates in your plugin, and call all your meta data there.
Example:
```
/* Filter the single_template with our custom function*/
add_filter('single_template', 'my_custom_template');
function my_custom_template($single) {
global $post;
/* Checks for single template by post type */
if ( $post->post_type == 'POST TYPE NAME' ) {
if ( file_exists( PLUGIN_PATH . '/Custom_File.php' ) ) {
return PLUGIN_PATH . '/Custom_File.php';
}
}
return $single;
}
```
You can refine that further and add a function to check to see if the theme has single-yourposttype.php and to use that one if it exists instead of your plugin version, allowing for easy overrides by developers. Example:
```
$themeurl = get_theme_file_path("/single-yourposttype.php");
$pluginurl = plugin_dir_path( dirname( __FILE__ ) ) . 'single-yourposttype.php';
if( file_exists( $themeurl ) ) {
include( $themeurl );
} elseif( file_exists( $pluginurl ) ) {
require "$pluginurl";
}
```
I hope that helps. |
356,455 | <p>I'm making some changes to a custom template for a website that wants to add the woocommerce support to create a little shop.
I've followed the instruction to add the theme support to the theme, in my function file I have added: </p>
<pre><code>add_theme_support('woocommerce');
</code></pre>
<p>and the relative hook <code>after_setup_theme</code>. I'm not experienced with this plugin, it's the first time I'm using it and I'm still reading the docs. Can anyone explain to me how I can customize the woocommerce templates to use bootstrap 4 and how I can display the products or the store pages on the index of my theme? will the <code>get_template_part('woocommerce/template-name')</code> work or there are some particular procedure to follow?</p>
| [
{
"answer_id": 356483,
"author": "Krishan Kaushik",
"author_id": 175251,
"author_profile": "https://wordpress.stackexchange.com/users/175251",
"pm_score": 0,
"selected": false,
"text": "<p>You can change your \"reading Settings\" in Settings menu,</p>\n\n<p>Please select \"Your home page displays\" = check to a static page and select shop from the dropdown menu.</p>\n\n<p>after these changes your index page will be shop page.</p>\n"
},
{
"answer_id": 356488,
"author": "salman creation",
"author_id": 87367,
"author_profile": "https://wordpress.stackexchange.com/users/87367",
"pm_score": 2,
"selected": true,
"text": "<p>Follow This and Make sure Your Shop or which page you want for default Home page and Then Save Button.</p>\n\n<p><a href=\"https://i.stack.imgur.com/2oGpx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2oGpx.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/nWkY2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nWkY2.png\" alt=\"enter image description here\"></a></p>\n\n<p>Thanks</p>\n"
}
] | 2020/01/15 | [
"https://wordpress.stackexchange.com/questions/356455",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177581/"
] | I'm making some changes to a custom template for a website that wants to add the woocommerce support to create a little shop.
I've followed the instruction to add the theme support to the theme, in my function file I have added:
```
add_theme_support('woocommerce');
```
and the relative hook `after_setup_theme`. I'm not experienced with this plugin, it's the first time I'm using it and I'm still reading the docs. Can anyone explain to me how I can customize the woocommerce templates to use bootstrap 4 and how I can display the products or the store pages on the index of my theme? will the `get_template_part('woocommerce/template-name')` work or there are some particular procedure to follow? | Follow This and Make sure Your Shop or which page you want for default Home page and Then Save Button.
[](https://i.stack.imgur.com/2oGpx.png)
[](https://i.stack.imgur.com/nWkY2.png)
Thanks |
356,499 | <p>First of I am pretty new to this so sorry if this has been asked before but I could not find the right answer for me.</p>
<p>I have this dropdown on my website<a href="https://i.stack.imgur.com/9LObW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9LObW.png" alt="enter image description here"></a></p>
<p>from compare-tech(.)fr</p>
<p>I am trying to remove "Toutes les catégories" and make "Acheter" the default value.
I have tried adding a function to wordpress but it did not work, I tried : (again I am new to this)</p>
<pre><code>function wp_dropdown_categories( $args = '' ) { $defaults = array( 'selected' => 2, );
</code></pre>
<p>Here are some more informations about the html code :</p>
<p><a href="https://i.stack.imgur.com/lj17q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lj17q.png" alt="enter image description here"></a></p>
<p>Thanks very much to anyone you would be able to help me ! </p>
| [
{
"answer_id": 356477,
"author": "Paul Elrich",
"author_id": 160341,
"author_profile": "https://wordpress.stackexchange.com/users/160341",
"pm_score": 1,
"selected": false,
"text": "<p>I don't believe that custom post types are a part of ACF. I use custom post type generators to add post types. <a href=\"https://www.wp-hasty.com/tools/wordpress-custom-post-type-generator/\" rel=\"nofollow noreferrer\">This is the one that I use</a>. You would just need to paste the resulting code at the bottom of your theme's functions.php file.</p>\n"
},
{
"answer_id": 356481,
"author": "Krishan Kaushik",
"author_id": 175251,
"author_profile": "https://wordpress.stackexchange.com/users/175251",
"pm_score": -1,
"selected": false,
"text": "<p>You need custom post type UI Plugin to create a post type like \"posts\"</p>\n\n<p>Link - <a href=\"https://wordpress.org/plugins/custom-post-type-ui/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/custom-post-type-ui/</a></p>\n"
}
] | 2020/01/16 | [
"https://wordpress.stackexchange.com/questions/356499",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180655/"
] | First of I am pretty new to this so sorry if this has been asked before but I could not find the right answer for me.
I have this dropdown on my website[](https://i.stack.imgur.com/9LObW.png)
from compare-tech(.)fr
I am trying to remove "Toutes les catégories" and make "Acheter" the default value.
I have tried adding a function to wordpress but it did not work, I tried : (again I am new to this)
```
function wp_dropdown_categories( $args = '' ) { $defaults = array( 'selected' => 2, );
```
Here are some more informations about the html code :
[](https://i.stack.imgur.com/lj17q.png)
Thanks very much to anyone you would be able to help me ! | I don't believe that custom post types are a part of ACF. I use custom post type generators to add post types. [This is the one that I use](https://www.wp-hasty.com/tools/wordpress-custom-post-type-generator/). You would just need to paste the resulting code at the bottom of your theme's functions.php file. |
356,513 | <p>Brand new WordPress install with Avade Theme installed on RPi 4 - works fine when I access it on <code>http://203.0.113.111/index.php</code> from an external connection, but if I remove the <code>index.php</code> I get nothing - connection refused.</p>
<p>Is this normal behaviour? Shouldn't I get redirected to the WP installs index page right away? I've forwarded port 80 in my router to the Pi's internal IP, so I can't get my head around this.</p>
<p>I even modified the <code>.htaccess</code> in <code>/var/www/html</code> with these lines:</p>
<pre><code>DirectoryIndex index.html index.php
</code></pre>
<p>but ALAS - even though I think it should work just fine I don't get why I have to write the <code>index.php</code> in my web-browser. Of course a direct DNS forward could do the trick here, but common? That's just symptom-treatment, right? </p>
<p>Can anyone give me a pointer in the right direction?</p>
<p>EDIT: It's the same when I try to access my web servers internal IP from the LAN - I have to input <code>index.php</code> if I must reach the WP-site.</p>
<p>EDIT 2: from @kero's comment: I rewrote <code>AllowOverride</code> in Apache conf from <code>None</code> to <code>ALL</code> and restarted Apache but still nothing.</p>
<p>... still changes nothing after an Apache service restart.</p>
| [
{
"answer_id": 356515,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Is this normal behaviour?</p>\n</blockquote>\n\n<p>Yes. On a default Apache install, only <code>index.html</code> is set as the DirectoryIndex (the default setting).</p>\n\n<p>Either in the appropriate <code><VirtualHost></code> container, or main server config you need to add a <code><Directory></code> section that specifically targets the defined document root directory.</p>\n\n<p>For example:</p>\n\n<pre><code>DocumentRoot /var/www/html\n\n<Directory \"/var/www/html\">\n # Allow public access to the site\n Require all granted\n\n # FollowSymLinks is required for mod_rewrite\n # (Although this is actually the default server setting)\n Options FollowSymLinks\n\n # Allow mod_dir to serve index.php by default\n DirectoryIndex index.php\n\n # Give full access to htaccess (optional)\n # Strictly speaking you only need \"FileInfo\" for mod_rewrite\n # - Alternatively place all your htaccess directives here...\n AllowOverride All\n</Directory>\n</code></pre>\n\n<p>You will then need to restart Apache.</p>\n\n<p>mod_dir also needs to be enabled, but this should be loaded by default.</p>\n"
},
{
"answer_id": 356534,
"author": "IT Blacksmith",
"author_id": 181158,
"author_profile": "https://wordpress.stackexchange.com/users/181158",
"pm_score": 2,
"selected": true,
"text": "<p>I got it to work ! Yey!</p>\n\n<p>The answer lay somewhere in the General settings of the wp-admin site and my dyn account. I delted my dyn record from their site temporarely. Then I edited the configuration of my wordpress-site and folder in wp-admin. I changed it to the external IP and then it worked without index.php right away. Then I changed the values back to my dyndns account: <a href=\"http://godset.raspberryip.com\" rel=\"nofollow noreferrer\">http://godset.raspberryip.com</a> and VOILA - no index.php needs to be written and everything works. Had to edit the site url though PHPmydamin since the WP-site was down due to this change I made.</p>\n\n<p>Not sure what the problem was though... But thnks to all that helped.</p>\n"
}
] | 2020/01/16 | [
"https://wordpress.stackexchange.com/questions/356513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181158/"
] | Brand new WordPress install with Avade Theme installed on RPi 4 - works fine when I access it on `http://203.0.113.111/index.php` from an external connection, but if I remove the `index.php` I get nothing - connection refused.
Is this normal behaviour? Shouldn't I get redirected to the WP installs index page right away? I've forwarded port 80 in my router to the Pi's internal IP, so I can't get my head around this.
I even modified the `.htaccess` in `/var/www/html` with these lines:
```
DirectoryIndex index.html index.php
```
but ALAS - even though I think it should work just fine I don't get why I have to write the `index.php` in my web-browser. Of course a direct DNS forward could do the trick here, but common? That's just symptom-treatment, right?
Can anyone give me a pointer in the right direction?
EDIT: It's the same when I try to access my web servers internal IP from the LAN - I have to input `index.php` if I must reach the WP-site.
EDIT 2: from @kero's comment: I rewrote `AllowOverride` in Apache conf from `None` to `ALL` and restarted Apache but still nothing.
... still changes nothing after an Apache service restart. | I got it to work ! Yey!
The answer lay somewhere in the General settings of the wp-admin site and my dyn account. I delted my dyn record from their site temporarely. Then I edited the configuration of my wordpress-site and folder in wp-admin. I changed it to the external IP and then it worked without index.php right away. Then I changed the values back to my dyndns account: <http://godset.raspberryip.com> and VOILA - no index.php needs to be written and everything works. Had to edit the site url though PHPmydamin since the WP-site was down due to this change I made.
Not sure what the problem was though... But thnks to all that helped. |
356,575 | <p>I have a coding noob question if someone wouldn't mind taking a squiz. Trying to get the title placed on the same line as the label, i.e</p>
<blockquote>
<p>Label: Title</p>
</blockquote>
<p>Currently it's formatted as:</p>
<blockquote>
<p>Label:</p>
<p>Title</p>
</blockquote>
<pre><code><p>
<?php echo apply_filters('cm_tooltip_parse', 'Label: ', true); ?>
<?php if ( generate_show_title() ) {
the_title();
}
?>
</p>
</code></pre>
<p>Also tried:</p>
<pre><code><p>
<?php echo apply_filters('cm_tooltip_parse', 'Label: ', true);
if ( generate_show_title() ) {
the_title();
}
?>
</p>
</code></pre>
<p>Usually I'm OK with basic formatting but something about the filter must be forcing the break,</p>
<p>Thanks,</p>
<p>Hi Tim I have included the complete code below to see how it is affecting this.</p>
<p>Using Tim's code 'Label' and 'Title' are now on the same line but (and as he pointed out) despite the trim I still have a space occurring underneath that line ('Published On' starts a new paragraph). If I remove the <code><p></code> before <code>'Label: ',</code> and <code>'</p>',</code> after it and put a <code><br /></code> at the end I get the formatting I want but the tooltip is no longer available for <code>'Label: '</code></p>
<pre><code><p>
<?php
echo ! generate_show_title() ?: trim( apply_filters( 'cm_tooltip_parse', the_title( 'Label: ', false ), true ), " \t\n\r\0\x0B" );
?><br />
Published On: <time datetime="<?php echo esc_attr( get_the_date( 'c' ) ); ?>"><?php echo esc_html( get_the_date() );
?></time><br />
<?php if( get_field('date_updated') ): ?>
Updated On: <?php the_field('date_updated'); ?><br />
<?php endif; ?>
</p>
</code></pre>
| [
{
"answer_id": 356533,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>Much of the code for any page, including header and footer, comes from your theme.</p>\n\n<p>If you want to create fully custom code, your best bet is to create a child theme (which just means creating a \"style.css\" file with some comments that refer to the parent theme, which is what you're currently using) and inside the child theme, create custom templates. It's there where you can add your own HTML and a loop to grab the content for each page (the part you edit in wp-admin).</p>\n"
},
{
"answer_id": 356536,
"author": "Waldo Rabie",
"author_id": 172667,
"author_profile": "https://wordpress.stackexchange.com/users/172667",
"pm_score": 0,
"selected": false,
"text": "<p>Open up the root directory of your Wordpress folder and then navigate to <code>wp-content/themes/</code> to see all the installed themes. Select the theme you're using and that folder will contain all theme specific code, including template files. </p>\n"
},
{
"answer_id": 356568,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>As mentioned elsewhere here, the display of your posts/pages depends on the theme that you are using. And making changes to the theme's code is not recommended, as any changes will be overwritten with a theme update. That's why you would create and activate a Child Theme to make changes. (Although you can make simple CSS changes via Admin, Themes, Customization, Additional CSS screen.)</p>\n\n<p>But if you really want to know how to change a specific look of a page, without changing the theme, Child Themes is what you want to do. Then you can add your customized page code to modify how things look.</p>\n\n<p>For this, you need to understand how themes work, and how they are 'built'. You should start here: <a href=\"https://developer.wordpress.org/themes/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/</a> . Then, look at 'theme hierarchy' to understand what theme template file is used to 'build' the post/page. There are also manu google/bings/ducks on how to build themes, create Child Themes, and the theme hierarchy. </p>\n"
},
{
"answer_id": 356576,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than editing Wordpress or your theme's source code you're better off using the \"Additional CSS\" option found while customizing your theme appearance within the admin menu.</p>\n\n<p>Using Google Chrome or similar, load your up page, right click on the header region then select \"Inspect\". You will see on the left of your screen the CSS styles associated with your page. </p>\n\n<p>In my case the header was called \"<strong>header-layout-1</strong>\". Yours might be different.</p>\n\n<p>While editing the \"Additional CSS\" add the following line;</p>\n\n<pre><code>.header-layout-1 {display:none;}\n</code></pre>\n\n<p>Save your changes and reload your page. Your header should be gone.</p>\n\n<p>Follow the same steps for the footer or anything else you don't want displayed.</p>\n\n<p><a href=\"https://en.support.wordpress.com/custom-design/editing-css/\" rel=\"nofollow noreferrer\">More information from Wordpress</a></p>\n"
}
] | 2020/01/17 | [
"https://wordpress.stackexchange.com/questions/356575",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163675/"
] | I have a coding noob question if someone wouldn't mind taking a squiz. Trying to get the title placed on the same line as the label, i.e
>
> Label: Title
>
>
>
Currently it's formatted as:
>
> Label:
>
>
> Title
>
>
>
```
<p>
<?php echo apply_filters('cm_tooltip_parse', 'Label: ', true); ?>
<?php if ( generate_show_title() ) {
the_title();
}
?>
</p>
```
Also tried:
```
<p>
<?php echo apply_filters('cm_tooltip_parse', 'Label: ', true);
if ( generate_show_title() ) {
the_title();
}
?>
</p>
```
Usually I'm OK with basic formatting but something about the filter must be forcing the break,
Thanks,
Hi Tim I have included the complete code below to see how it is affecting this.
Using Tim's code 'Label' and 'Title' are now on the same line but (and as he pointed out) despite the trim I still have a space occurring underneath that line ('Published On' starts a new paragraph). If I remove the `<p>` before `'Label: ',` and `'</p>',` after it and put a `<br />` at the end I get the formatting I want but the tooltip is no longer available for `'Label: '`
```
<p>
<?php
echo ! generate_show_title() ?: trim( apply_filters( 'cm_tooltip_parse', the_title( 'Label: ', false ), true ), " \t\n\r\0\x0B" );
?><br />
Published On: <time datetime="<?php echo esc_attr( get_the_date( 'c' ) ); ?>"><?php echo esc_html( get_the_date() );
?></time><br />
<?php if( get_field('date_updated') ): ?>
Updated On: <?php the_field('date_updated'); ?><br />
<?php endif; ?>
</p>
``` | Much of the code for any page, including header and footer, comes from your theme.
If you want to create fully custom code, your best bet is to create a child theme (which just means creating a "style.css" file with some comments that refer to the parent theme, which is what you're currently using) and inside the child theme, create custom templates. It's there where you can add your own HTML and a loop to grab the content for each page (the part you edit in wp-admin). |
356,609 | <p>I'd like to know how to validate custom fields and return error notice (if necessary) before a custom post type is inserted into the database.</p>
<p>After a little research I found one similar question dating back ~10 years ago, I was hoping for a solution now, it seems like a pretty simple filter to implement.</p>
<p>Looking at <code>wp-includes/post.php</code>, we don't have an easy solution to this. :(</p>
| [
{
"answer_id": 356610,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 1,
"selected": false,
"text": "<p>I've used jQuery Validate for this sort of thing in a previous project and it worked exactly as I wanted. You have to enqueue the script and then write the validation out but it really did offer me a great deal of control over what was being done.</p>\n\n<p><a href=\"https://jqueryvalidation.org\" rel=\"nofollow noreferrer\">https://jqueryvalidation.org</a></p>\n"
},
{
"answer_id": 356632,
"author": "Caio Mar",
"author_id": 54189,
"author_profile": "https://wordpress.stackexchange.com/users/54189",
"pm_score": 2,
"selected": false,
"text": "<p>I hacked the sh*t out of it. Here is my uggliest solution ever to a simple problem. I am not really happy with this, but it will have to do.</p>\n\n<p>For the sake of this example, I will use a custom post type called <code>book</code> and we're gonna validate a field called <code>ISBN</code>. This solution uses <code>PHP Session</code> and <code>header redirect</code>.</p>\n\n<p>Here we go...</p>\n\n<p><strong>Step 1 - Data Validation</strong></p>\n\n<p>The data validation happens using the filter hook <code>wp_insert_post_data</code>, right before the data is inserted in the database. If it is invalid, we set an invalid flag and redirect the user before the data is inserted into the database.</p>\n\n<pre><code>function pre_insert_book($data, $postarr)\n{\n if ($data['post_type'] === \"book\" && in_array($data['post_status'], ['publish', 'draft', 'pending']) && !empty($_POST) && isset($_POST['ISBN'])) {\n $ISBN = sanitize_text_field($_POST['ISBN']);\n if (empty($ISBN)) {\n session_start();\n $_SESSION['POST'] = $_POST;\n header(\"Location: \" . admin_url('post-new.php?post_type=book&invalid=empty_ISBN'));\n exit;\n } elseif (!validade_ISBN($ISBN)) {\n session_start();\n $_SESSION['POST'] = $_POST;\n header(\"Location: \" . admin_url('post-new.php?post_type=book&invalid=invalid_ISBN'));\n exit;\n }\n }\n return $data;\n}\nadd_filter('wp_insert_post_data', 'pre_insert_book', 10, 2);\n</code></pre>\n\n<p><strong>Step 2 - Display error notice</strong></p>\n\n<p>If an invalid flag is thrown, we display an error to the user. We also preserve the book title so the data isn't lost on form submission. I'm sure this could be done elsewhere.</p>\n\n<pre><code>function check_insert_book_error_notices()\n{\n global $current_screen, $post;\n\n if ($current_screen->parent_file === \"edit.php?post_type=book\" && isset($_GET['invalid'])) {\n\n session_start();\n\n // We want to keep the book title like so (and other values if necessary)\n if (isset($_SESSION[\"POST\"]) && isset($_SESSION[\"POST\"]['post_title']))\n $post->post_title = $_SESSION[\"POST\"]['post_title'];\n\n if (esc_attr($_GET['invalid']) === \"empty_ISBN\") {\n echo '<div class=\"error\"><p>ISBN number cant be empty</p></div>';\n } elseif (esc_attr($_GET['invalid']) === \"invalid_ISBN\") {\n echo '<div class=\"error\"><p>ISBN is not valid</p></div>';\n }\n }\n}\nadd_action('admin_notices', 'check_insert_book_error_notices');\n</code></pre>\n\n<p><strong>Step 3 - Dealing with the ISBN form field and Session</strong></p>\n\n<p>It's not fun to return to an empty form when a error occurs, nor it is ever a good practice to leave a session open. So we deal with this here.</p>\n\n<pre><code>function load_custom_book_meta_boxes()\n{\n add_meta_box('isbn-form', 'Book data', array($this, 'custom_form_for_book_post_type'), 'book', 'normal', 'high');\n}\nadd_action('add_meta_boxes', 'load_custom_book_meta_boxes');\n\nfunction custom_form_for_book_post_type($post)\n{\n\n session_start();\n\n $ISBN_previous_value = \"\";\n if (isset($_SESSION[\"POST\"]) && isset($_SESSION[\"POST\"]['ISBN']))\n $ISBN_previous_value = sanitize_text_field($_SESSION[\"POST\"]['ISBN']);\n\n session_destroy();\n\n ob_start(); ?>\n\n <div id=\"isbn-form-container\">\n <form class=\"isbn-form\" method=\"post\" action=\"\">\n <table>\n <tr class=\"isbn-row\">\n <td><label for=\"ISBN\">Book ISBN</label></td>\n <td><input type=\"number\" id=\"ISBN\" class=\"required\" name=\"ISBN\" value=\"<?php echo $ISBN_previous_value; ?>\" autocomplete=\"off\" required></td>\n </tr>\n </table>\n </form>\n </div>\n\n<?php ob_end_flush();\n}\n</code></pre>\n\n<p>Everything seems to be working fine; I only did a bit of testing and will return later to do some more.</p>\n\n<p>Hope it helps some folks wanting something similar.</p>\n"
}
] | 2020/01/17 | [
"https://wordpress.stackexchange.com/questions/356609",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54189/"
] | I'd like to know how to validate custom fields and return error notice (if necessary) before a custom post type is inserted into the database.
After a little research I found one similar question dating back ~10 years ago, I was hoping for a solution now, it seems like a pretty simple filter to implement.
Looking at `wp-includes/post.php`, we don't have an easy solution to this. :( | I hacked the sh\*t out of it. Here is my uggliest solution ever to a simple problem. I am not really happy with this, but it will have to do.
For the sake of this example, I will use a custom post type called `book` and we're gonna validate a field called `ISBN`. This solution uses `PHP Session` and `header redirect`.
Here we go...
**Step 1 - Data Validation**
The data validation happens using the filter hook `wp_insert_post_data`, right before the data is inserted in the database. If it is invalid, we set an invalid flag and redirect the user before the data is inserted into the database.
```
function pre_insert_book($data, $postarr)
{
if ($data['post_type'] === "book" && in_array($data['post_status'], ['publish', 'draft', 'pending']) && !empty($_POST) && isset($_POST['ISBN'])) {
$ISBN = sanitize_text_field($_POST['ISBN']);
if (empty($ISBN)) {
session_start();
$_SESSION['POST'] = $_POST;
header("Location: " . admin_url('post-new.php?post_type=book&invalid=empty_ISBN'));
exit;
} elseif (!validade_ISBN($ISBN)) {
session_start();
$_SESSION['POST'] = $_POST;
header("Location: " . admin_url('post-new.php?post_type=book&invalid=invalid_ISBN'));
exit;
}
}
return $data;
}
add_filter('wp_insert_post_data', 'pre_insert_book', 10, 2);
```
**Step 2 - Display error notice**
If an invalid flag is thrown, we display an error to the user. We also preserve the book title so the data isn't lost on form submission. I'm sure this could be done elsewhere.
```
function check_insert_book_error_notices()
{
global $current_screen, $post;
if ($current_screen->parent_file === "edit.php?post_type=book" && isset($_GET['invalid'])) {
session_start();
// We want to keep the book title like so (and other values if necessary)
if (isset($_SESSION["POST"]) && isset($_SESSION["POST"]['post_title']))
$post->post_title = $_SESSION["POST"]['post_title'];
if (esc_attr($_GET['invalid']) === "empty_ISBN") {
echo '<div class="error"><p>ISBN number cant be empty</p></div>';
} elseif (esc_attr($_GET['invalid']) === "invalid_ISBN") {
echo '<div class="error"><p>ISBN is not valid</p></div>';
}
}
}
add_action('admin_notices', 'check_insert_book_error_notices');
```
**Step 3 - Dealing with the ISBN form field and Session**
It's not fun to return to an empty form when a error occurs, nor it is ever a good practice to leave a session open. So we deal with this here.
```
function load_custom_book_meta_boxes()
{
add_meta_box('isbn-form', 'Book data', array($this, 'custom_form_for_book_post_type'), 'book', 'normal', 'high');
}
add_action('add_meta_boxes', 'load_custom_book_meta_boxes');
function custom_form_for_book_post_type($post)
{
session_start();
$ISBN_previous_value = "";
if (isset($_SESSION["POST"]) && isset($_SESSION["POST"]['ISBN']))
$ISBN_previous_value = sanitize_text_field($_SESSION["POST"]['ISBN']);
session_destroy();
ob_start(); ?>
<div id="isbn-form-container">
<form class="isbn-form" method="post" action="">
<table>
<tr class="isbn-row">
<td><label for="ISBN">Book ISBN</label></td>
<td><input type="number" id="ISBN" class="required" name="ISBN" value="<?php echo $ISBN_previous_value; ?>" autocomplete="off" required></td>
</tr>
</table>
</form>
</div>
<?php ob_end_flush();
}
```
Everything seems to be working fine; I only did a bit of testing and will return later to do some more.
Hope it helps some folks wanting something similar. |
356,624 | <p>How can I have specific plugins only active for one specific user role (or potentially an array of user roles)?</p>
<p>Is there something I can add to my <code>functions.php</code> in the child theme to only use a specific plugin for a specific user role?</p>
<p>I have tried various answers from here and articles but nothing seems to offer what I need.</p>
<p><strong>Update:</strong></p>
<p>I've tried the below code (as a test) and it works in that if an admin accesses the site it disables the plugin, but once it's disabled it stays disabled for everyone. It needs to asses the current user and activate or reactivate depending on their role.</p>
<pre><code>add_filter( 'option_active_plugins', 'custom_plugin_load_filter' );
function custom_plugin_load_filter( $plugins ) {
$user = wp_get_current_user();
if ( in_array( 'administrator', (array) $user->roles ) ) {
//unset( $plugins['additional-order-confirmation-email/additional-order-confirmation-email.php'] ); // change my-plugin-slug
$key = array_search( 'additional-order-confirmation-email/additional-order-confirmation-email.php' , $plugins );
if ( false !== $key ) {
unset( $plugins[$key] );
}
}
return $plugins;
}
</code></pre>
<p>If I change it to <code>!in_array</code> it remains active for admin users (correct) but also for guests (incorrect).</p>
| [
{
"answer_id": 356652,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>It's not a good idea to modify plugins if you can help it, as the plugin may be upated and you will lose your changes and need to redo them.</p>\n\n<p>Fortunately, that is not necessary in this case anyway, as you can the filter active plugins option instead. You will need the plugin slug for this:</p>\n\n<pre><code>add_filter( 'option_active_plugins', 'custom_plugin_load_filter' );\nfunction custom_plugin_load_filter( $plugins ) {\n $user = wp_get_current_user();\n if ( !in_array( 'sales_events', (array) $user->roles ) ) {\n unset( $plugins['my-plugin-slug'] ); // change my-plugin-slug\n }\n return $plugins;\n}\n</code></pre>\n\n<p>Note as this will run on the plugins page also, it will probably prevent anyone without the role from disabling the plugin (as it will appear to be inactive to them.)</p>\n"
},
{
"answer_id": 357107,
"author": "Hector",
"author_id": 48376,
"author_profile": "https://wordpress.stackexchange.com/users/48376",
"pm_score": 0,
"selected": false,
"text": "<p>This is an answer based on the term \"Executing plugin\" in your question title.</p>\n\n<p>If you just want to run/execute a plugin for user roles, you don't need to prevent it from loading. My solution is to let WordPress load your plugin and manage it in your plugin.</p>\n\n<p>So, you could have codes like this:</p>\n\n<pre><code>// In the main plugin file that loads and initiate plugin functionalities.\n\nif ( ! current_user_can( 'manage_options' ) ) {\n return;\n}\n\ninclude 'plugin-file.php';\nnew myPlugin();\n</code></pre>\n\n<p>By using this solution, your plugin is active for all users, but it actually <strong>works only</strong> for users with <code>manage_options</code> capability.</p>\n\n<p>It will not make plugin <strong>Inactive</strong> for some users, but it is a clean solution to run functionality (Execute) only for some users.</p>\n"
}
] | 2020/01/17 | [
"https://wordpress.stackexchange.com/questions/356624",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117919/"
] | How can I have specific plugins only active for one specific user role (or potentially an array of user roles)?
Is there something I can add to my `functions.php` in the child theme to only use a specific plugin for a specific user role?
I have tried various answers from here and articles but nothing seems to offer what I need.
**Update:**
I've tried the below code (as a test) and it works in that if an admin accesses the site it disables the plugin, but once it's disabled it stays disabled for everyone. It needs to asses the current user and activate or reactivate depending on their role.
```
add_filter( 'option_active_plugins', 'custom_plugin_load_filter' );
function custom_plugin_load_filter( $plugins ) {
$user = wp_get_current_user();
if ( in_array( 'administrator', (array) $user->roles ) ) {
//unset( $plugins['additional-order-confirmation-email/additional-order-confirmation-email.php'] ); // change my-plugin-slug
$key = array_search( 'additional-order-confirmation-email/additional-order-confirmation-email.php' , $plugins );
if ( false !== $key ) {
unset( $plugins[$key] );
}
}
return $plugins;
}
```
If I change it to `!in_array` it remains active for admin users (correct) but also for guests (incorrect). | It's not a good idea to modify plugins if you can help it, as the plugin may be upated and you will lose your changes and need to redo them.
Fortunately, that is not necessary in this case anyway, as you can the filter active plugins option instead. You will need the plugin slug for this:
```
add_filter( 'option_active_plugins', 'custom_plugin_load_filter' );
function custom_plugin_load_filter( $plugins ) {
$user = wp_get_current_user();
if ( !in_array( 'sales_events', (array) $user->roles ) ) {
unset( $plugins['my-plugin-slug'] ); // change my-plugin-slug
}
return $plugins;
}
```
Note as this will run on the plugins page also, it will probably prevent anyone without the role from disabling the plugin (as it will appear to be inactive to them.) |
356,663 | <p>I'm adding my query arg as such:</p>
<pre><code>add_filter( 'query_vars', function( $qvars ) {
$qvars[] = 'my_query_var';
return $qvars;
});
</code></pre>
<p>And when I do:</p>
<pre><code>add_action( 'init', function() {
$string = get_query_var( 'my_query_var' );
echo( $string );
});
</code></pre>
<p>It's not available, yet if I hook very, very late, like <code>loop_start</code>, it's there. What exactly am I missing? The string I passed is there if I inspect <code>$_GET</code>.</p>
| [
{
"answer_id": 356666,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>query_vars</code> filter does not run until after <code>init</code>. The earliest hook you can use <code>get_query_var()</code> is <a href=\"https://developer.wordpress.org/reference/hooks/parse_request/\" rel=\"nofollow noreferrer\"><code>parse_request</code></a>, which runs after <code>init</code>, but before <code>send_headers</code>, <code>wp</code>, <code>template_redirect</code>, and <code>template_include</code>.</p>\n"
},
{
"answer_id": 410909,
"author": "wpDev",
"author_id": 220017,
"author_profile": "https://wordpress.stackexchange.com/users/220017",
"pm_score": 0,
"selected": false,
"text": "<p>I had a lot of issues as well with firing the hook and parse_request didn't work but wp hook did.</p>\n<p>It is run in the main() WP method in which the $query_args are passed to parse_request(), as well as when send_headers() , query_posts() , handle_404(), and register_globals() are setup.</p>\n<pre><code>add_action( 'wp', function () {\n if ( '' !== get_query_var('cat') ) {\n // prevent redirections\n add_filter( 'pll_check_canonical_url', '__return_false' );\n }\n else {\n wp_die('not cat');\n }\n} );\n</code></pre>\n"
}
] | 2020/01/18 | [
"https://wordpress.stackexchange.com/questions/356663",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180512/"
] | I'm adding my query arg as such:
```
add_filter( 'query_vars', function( $qvars ) {
$qvars[] = 'my_query_var';
return $qvars;
});
```
And when I do:
```
add_action( 'init', function() {
$string = get_query_var( 'my_query_var' );
echo( $string );
});
```
It's not available, yet if I hook very, very late, like `loop_start`, it's there. What exactly am I missing? The string I passed is there if I inspect `$_GET`. | The `query_vars` filter does not run until after `init`. The earliest hook you can use `get_query_var()` is [`parse_request`](https://developer.wordpress.org/reference/hooks/parse_request/), which runs after `init`, but before `send_headers`, `wp`, `template_redirect`, and `template_include`. |
356,759 | <p>I need to rearrange the posts by ordering them from published date instead of alphabetical order in Menu posts selection panel, view all section.</p>
<p><a href="https://i.stack.imgur.com/2iBzb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2iBzb.jpg" alt="enter image description here"></a> </p>
<p>I want them to order as same way in the most recent posts in the view all section as well. </p>
<p>Is it possible to achieve this via a hook or any other code ?</p>
| [
{
"answer_id": 356772,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 2,
"selected": true,
"text": "<pre><code>add_action( 'pre_get_posts', 'AS_order_posts_in_menu_admin' );\nfunction AS_order_posts_in_menu_admin( $q ) {\n global $pagenow;\n if('nav-menus.php' !=$pagenow)\n return $q;\n\n if(isset($q->query_vars['post_type']) && $q->query_vars['post_type']== 'post'){\n $q->query_vars['orderby'] = 'date';\n $q->query_vars['order'] = \"DESC\";\n }\n return $q;\n}\n</code></pre>\n"
},
{
"answer_id": 356773,
"author": "Vitauts Stočka",
"author_id": 181289,
"author_profile": "https://wordpress.stackexchange.com/users/181289",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this filter.</p>\n\n<pre><code>add_filter('nav_menu_meta_box_object', function($post_type) {\n if ($post_type && 'page' === $post_type->name) {\n // Give pages a higher priority.\n $post_type->_default_query['orderby'] = 'post_date';\n $post_type->_default_query['order'] = 'DESC';\n add_meta_box( \"add-post-type-page\", $post_type->labels->name, 'wp_nav_menu_item_post_type_meta_box', 'nav-menus', 'side', 'core', $post_type );\n return null;\n }\n return $post_type;\n}, 10);\n</code></pre>\n"
}
] | 2020/01/20 | [
"https://wordpress.stackexchange.com/questions/356759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68403/"
] | I need to rearrange the posts by ordering them from published date instead of alphabetical order in Menu posts selection panel, view all section.
[](https://i.stack.imgur.com/2iBzb.jpg)
I want them to order as same way in the most recent posts in the view all section as well.
Is it possible to achieve this via a hook or any other code ? | ```
add_action( 'pre_get_posts', 'AS_order_posts_in_menu_admin' );
function AS_order_posts_in_menu_admin( $q ) {
global $pagenow;
if('nav-menus.php' !=$pagenow)
return $q;
if(isset($q->query_vars['post_type']) && $q->query_vars['post_type']== 'post'){
$q->query_vars['orderby'] = 'date';
$q->query_vars['order'] = "DESC";
}
return $q;
}
``` |
356,795 | <p>Working on a category page - taxonomy-product_cat.php - I want to list all the subcategories of that category page, with all its products. I would think it is simple enough but I cant get it to work.</p>
<p>I can list all categories of the shop with all subcategories and all products - So for example bags would list all products of the whole shop. </p>
<p>Or I can list the subcategories of just the category page - but without the products listed.</p>
<p>How can I list just the subcategories of the category page with their products?</p>
<p>The code I am using that works great, but loops all the categories in the shop, and not just the active category is:</p>
<pre><code>$args = array('taxonomy' => 'product_cat' ); $all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
$category_id = $cat->term_id;
$args2 = array('taxonomy' => $taxonomy,'parent' => $category_id,'hierarchical' => $hierarchical, 'orderby' => $orderby, 'order' => $order,'hide_empty' => $empty); $categories = get_categories( $args2 );
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo "<h2>".$sub_category->cat_name."</h2>";
$args = array( 'post_type' => 'product','product_cat' => $sub_category->slug, 'orderby' => $orderby, 'order' => $order);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<!--HTML HERE-->
<?php endwhile; wp_reset_query(); }}} ?>
</code></pre>
| [
{
"answer_id": 356801,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<p>The code below works for me in archive-product.php\nnot sure if it may also work in taxonomy-product_cat.php</p>\n\n<p><b>EDIT</b>\nI've added some lines of code to exclude posts previously outputted, since a post can belong to several categories and that's why you can find always the same posts </p>\n\n<pre><code> if(is_a(get_queried_object(),'WP_term')){\n $subs=get_terms('product_cat',array('parent'=>get_queried_object()->term_id));\n //var_dump($subs);\n $to_excude=[];\n foreach($subs as $sub){\n $args = array(\n 'post_type' => 'product',\n 'post_status'=>'publish',\n 'post__not_in' =>$to_excude,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'term_id',\n 'terms' => $sub->slug\n ),\n ),\n );\n $query = new WP_Query( $args );\n if($query->have_posts()):\n ?>\n <h4><?php echo $sub->name?></h4>\n <?php\n while($query->have_posts()):\n //\n $to_excude[]=get_the_ID();\n $query->the_post();\n the_title();\n // etc\n endwhile;\n endif;\n wp_reset_query(); \n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 357355,
"author": "Jon",
"author_id": 14416,
"author_profile": "https://wordpress.stackexchange.com/users/14416",
"pm_score": 0,
"selected": false,
"text": "<p>I cobbled this code together from different ideas online, and seems to work:</p>\n\n<pre><code><?php foreach ( $product_categories as $product_category ) {\n echo '<h2><a href=\"' . get_term_link( $product_category ) . '\">' . $product_category->name . '</a></h2>'; \n $args = array(\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $product_category->slug\n )\n ),\n 'post_type' => 'product', \n 'orderby' => 'name',\n 'order' => 'ASC', \n 'posts_per_page' => -1 \n\n ); \n\n $products = new WP_Query( $args ); \n while ( $products->have_posts() ) {\n $products->the_post(); ?>\n\n //HTML CODE HERE\n <div> <?php the_content(); ?> </div>\n <?php } } ?>\n</code></pre>\n\n<p>However I am having some issues ordering the outputted products - if anyone has any ideas. Changing the 2nd args <code>'order' => 'DESC'</code>\nor adding <code>'meta_key' => 'size', 'orderby' => 'meta_value_num'</code> <code></code>orderby` etc does not seem to affect the product order listing under the sun category titles.</p>\n"
}
] | 2020/01/20 | [
"https://wordpress.stackexchange.com/questions/356795",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14416/"
] | Working on a category page - taxonomy-product\_cat.php - I want to list all the subcategories of that category page, with all its products. I would think it is simple enough but I cant get it to work.
I can list all categories of the shop with all subcategories and all products - So for example bags would list all products of the whole shop.
Or I can list the subcategories of just the category page - but without the products listed.
How can I list just the subcategories of the category page with their products?
The code I am using that works great, but loops all the categories in the shop, and not just the active category is:
```
$args = array('taxonomy' => 'product_cat' ); $all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
$category_id = $cat->term_id;
$args2 = array('taxonomy' => $taxonomy,'parent' => $category_id,'hierarchical' => $hierarchical, 'orderby' => $orderby, 'order' => $order,'hide_empty' => $empty); $categories = get_categories( $args2 );
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo "<h2>".$sub_category->cat_name."</h2>";
$args = array( 'post_type' => 'product','product_cat' => $sub_category->slug, 'orderby' => $orderby, 'order' => $order);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<!--HTML HERE-->
<?php endwhile; wp_reset_query(); }}} ?>
``` | The code below works for me in archive-product.php
not sure if it may also work in taxonomy-product\_cat.php
**EDIT**
I've added some lines of code to exclude posts previously outputted, since a post can belong to several categories and that's why you can find always the same posts
```
if(is_a(get_queried_object(),'WP_term')){
$subs=get_terms('product_cat',array('parent'=>get_queried_object()->term_id));
//var_dump($subs);
$to_excude=[];
foreach($subs as $sub){
$args = array(
'post_type' => 'product',
'post_status'=>'publish',
'post__not_in' =>$to_excude,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $sub->slug
),
),
);
$query = new WP_Query( $args );
if($query->have_posts()):
?>
<h4><?php echo $sub->name?></h4>
<?php
while($query->have_posts()):
//
$to_excude[]=get_the_ID();
$query->the_post();
the_title();
// etc
endwhile;
endif;
wp_reset_query();
}
}
``` |
356,800 | <p>I would like to have different types of posts on my blog, e.g.: articles, film descriptions, book descriptions, links with short descriptions, quotations, historical events, characters, artwork, musical works, terms, etc. They should be grouped in hierarchical catalogues and hierarchical tags. Theoretically, this plug-in provides me with the possibility to do it: <a href="https://wordpress.org/plugins/custom-post-type-ui/" rel="nofollow noreferrer">https://wordpress.org/plugins/custom-post-type-ui/</a>. There is only a problem with it – custom post types don’t appear on the home page: <a href="https://wordpress.org/support/topic/custom-post-type-dont-appear-in-the-main-colllection/" rel="nofollow noreferrer">https://wordpress.org/support/topic/custom-post-type-dont-appear-in-the-main-colllection/</a>. I’m learning php, but it will take a lot of time before I get the right knowledge. I could hire a programmer, but first I would like to do a good research. I believe that there is another simpler way. Does anyone know it?</p>
| [
{
"answer_id": 356801,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<p>The code below works for me in archive-product.php\nnot sure if it may also work in taxonomy-product_cat.php</p>\n\n<p><b>EDIT</b>\nI've added some lines of code to exclude posts previously outputted, since a post can belong to several categories and that's why you can find always the same posts </p>\n\n<pre><code> if(is_a(get_queried_object(),'WP_term')){\n $subs=get_terms('product_cat',array('parent'=>get_queried_object()->term_id));\n //var_dump($subs);\n $to_excude=[];\n foreach($subs as $sub){\n $args = array(\n 'post_type' => 'product',\n 'post_status'=>'publish',\n 'post__not_in' =>$to_excude,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'term_id',\n 'terms' => $sub->slug\n ),\n ),\n );\n $query = new WP_Query( $args );\n if($query->have_posts()):\n ?>\n <h4><?php echo $sub->name?></h4>\n <?php\n while($query->have_posts()):\n //\n $to_excude[]=get_the_ID();\n $query->the_post();\n the_title();\n // etc\n endwhile;\n endif;\n wp_reset_query(); \n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 357355,
"author": "Jon",
"author_id": 14416,
"author_profile": "https://wordpress.stackexchange.com/users/14416",
"pm_score": 0,
"selected": false,
"text": "<p>I cobbled this code together from different ideas online, and seems to work:</p>\n\n<pre><code><?php foreach ( $product_categories as $product_category ) {\n echo '<h2><a href=\"' . get_term_link( $product_category ) . '\">' . $product_category->name . '</a></h2>'; \n $args = array(\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $product_category->slug\n )\n ),\n 'post_type' => 'product', \n 'orderby' => 'name',\n 'order' => 'ASC', \n 'posts_per_page' => -1 \n\n ); \n\n $products = new WP_Query( $args ); \n while ( $products->have_posts() ) {\n $products->the_post(); ?>\n\n //HTML CODE HERE\n <div> <?php the_content(); ?> </div>\n <?php } } ?>\n</code></pre>\n\n<p>However I am having some issues ordering the outputted products - if anyone has any ideas. Changing the 2nd args <code>'order' => 'DESC'</code>\nor adding <code>'meta_key' => 'size', 'orderby' => 'meta_value_num'</code> <code></code>orderby` etc does not seem to affect the product order listing under the sun category titles.</p>\n"
}
] | 2020/01/20 | [
"https://wordpress.stackexchange.com/questions/356800",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178440/"
] | I would like to have different types of posts on my blog, e.g.: articles, film descriptions, book descriptions, links with short descriptions, quotations, historical events, characters, artwork, musical works, terms, etc. They should be grouped in hierarchical catalogues and hierarchical tags. Theoretically, this plug-in provides me with the possibility to do it: <https://wordpress.org/plugins/custom-post-type-ui/>. There is only a problem with it – custom post types don’t appear on the home page: <https://wordpress.org/support/topic/custom-post-type-dont-appear-in-the-main-colllection/>. I’m learning php, but it will take a lot of time before I get the right knowledge. I could hire a programmer, but first I would like to do a good research. I believe that there is another simpler way. Does anyone know it? | The code below works for me in archive-product.php
not sure if it may also work in taxonomy-product\_cat.php
**EDIT**
I've added some lines of code to exclude posts previously outputted, since a post can belong to several categories and that's why you can find always the same posts
```
if(is_a(get_queried_object(),'WP_term')){
$subs=get_terms('product_cat',array('parent'=>get_queried_object()->term_id));
//var_dump($subs);
$to_excude=[];
foreach($subs as $sub){
$args = array(
'post_type' => 'product',
'post_status'=>'publish',
'post__not_in' =>$to_excude,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $sub->slug
),
),
);
$query = new WP_Query( $args );
if($query->have_posts()):
?>
<h4><?php echo $sub->name?></h4>
<?php
while($query->have_posts()):
//
$to_excude[]=get_the_ID();
$query->the_post();
the_title();
// etc
endwhile;
endif;
wp_reset_query();
}
}
``` |
356,827 | <p>It's been approximately a month since <strong>i can no longer update any plugins or wordpress core on my website.</strong> When I attempt to update the website it get's knocked off line. Jetpack then reactivates the website for me after 5-8 minutes. When it comes back online I get this in the admin section:</p>
<blockquote>
<p>There has been a critical error on your website. Please check your
site admin email inbox for instructions.</p>
</blockquote>
<p>Unfortunately, i don't actually get that email. Thus no further information.</p>
<p>Despite these problems, I can continue to publish articles, and the rest of the website works as expected.</p>
<p>I've been reading up on what could possibly be the problem, and think it could have something to do with my webhosts settings (DigitalOcean) and directory permissions.</p>
<p>What do I need to look at to determine if directory permissions is the problem? Or what the problem could possible be, to have the website behave like this?</p>
<p>UPDATE:
I have looked at the <code>error.log</code> and I see the following lines repeated:</p>
<pre><code>[Tue Jan 21 09:15:26.128769 2020] [fcgid:warn] [pid 16817] [client 52.9.128.29:42158] mod_fcgid: stderr: PHP Fatal error: Uncaught Error: Call to undefined function get_header() in /var/www/clients/client1/web1/web/wp-content/themes/study-circle/index.php:13
[Tue Jan 21 09:15:26.128824 2020] [fcgid:warn] [pid 16817] [client 52.9.128.29:42158] mod_fcgid: stderr: Stack trace:
[Tue Jan 21 09:15:26.128832 2020] [fcgid:warn] [pid 16817] [client 52.9.128.29:42158] mod_fcgid: stderr: #0 {main}
[Tue Jan 21 09:15:26.128837 2020] [fcgid:warn] [pid 16817] [client 52.9.128.29:42158] mod_fcgid: stderr: thrown in /var/www/clients/client1/web1/web/wp-content/themes/study-circle/index.php on line 13
</code></pre>
<p>The index.php code looks normal to me...</p>
<pre><code><?php
/**
* The template for displaying home page.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package Study Circle
*/
get_header();
?>
<div class="container">
<div class="page_content">
<section class="site-main">
<div class="blog-post">
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post();
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content' );
endwhile;
// Previous/next post navigation.
the_posts_pagination();
else :
// If no content, include the "No posts found" template.
get_template_part( 'no-results', 'index' );
endif;
?>
</div><!-- blog-post -->
</section>
<?php get_sidebar();?>
<div class="clear"></div>
</div><!-- site-aligner -->
</div><!-- content -->
<?php get_footer(); ?>
</code></pre>
<p>And the <code>get_header</code> Function from wp-includes/general-template.php:</p>
<pre><code>function get_header( $name = null ) {
/**
* Fires before the header template file is loaded.
*
* @since 2.1.0
* @since 2.8.0 $name parameter added.
*
* @param string|null $name Name of the specific header file to use. null for the default header.
*/
do_action( 'get_header', $name );
$templates = array();
$name = (string) $name;
if ( '' !== $name ) {
$templates[] = "header-{$name}.php";
}
$templates[] = 'header.php';
locate_template( $templates, true );
}
</code></pre>
| [
{
"answer_id": 356833,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Besides looking at your inbox for any messages that WP might send you (they don't always get sent), look at the error.log file in the site root and wp-admin folders. That will tell you where the error is.</p>\n\n<p>If it is a plugin, then rename that plugin's folder temporarily, then try the update again. You could also rename the entire plugin folder to temporarily disable all plugins. And you might consider reverting to one of the 'twenty' themes to do your update.</p>\n\n<p>Once you have updated WP (and updated your PHP version, which may also be the problem; contact your hosting place for instructions on that), you can move back to your old theme. Then make a new plugins folder, and move each plugin folder individually to the new plugins folder. After each move, check the admin page, and do the 'update' check. Repeat for each plugin. (And update your theme, if needed.)</p>\n\n<p>Your issue shows the importance of keeping WP - core, themes, and plugins - updated. Less problems that way. (And the importance of updating your PHP version.)</p>\n"
},
{
"answer_id": 358565,
"author": "rohrl77",
"author_id": 112790,
"author_profile": "https://wordpress.stackexchange.com/users/112790",
"pm_score": 1,
"selected": true,
"text": "<p>In the end I could not solve this myself. I hired a freelancer who specialised in WP development. As it turned out, it was a plugin (OptimizePress 2) that was responsible for this problem, however, the issue remained even when that plugin was deactived. How this is possible, I don't know, and can't give any real technical details on. </p>\n\n<p>Just wanted to report back.</p>\n"
}
] | 2020/01/20 | [
"https://wordpress.stackexchange.com/questions/356827",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112790/"
] | It's been approximately a month since **i can no longer update any plugins or wordpress core on my website.** When I attempt to update the website it get's knocked off line. Jetpack then reactivates the website for me after 5-8 minutes. When it comes back online I get this in the admin section:
>
> There has been a critical error on your website. Please check your
> site admin email inbox for instructions.
>
>
>
Unfortunately, i don't actually get that email. Thus no further information.
Despite these problems, I can continue to publish articles, and the rest of the website works as expected.
I've been reading up on what could possibly be the problem, and think it could have something to do with my webhosts settings (DigitalOcean) and directory permissions.
What do I need to look at to determine if directory permissions is the problem? Or what the problem could possible be, to have the website behave like this?
UPDATE:
I have looked at the `error.log` and I see the following lines repeated:
```
[Tue Jan 21 09:15:26.128769 2020] [fcgid:warn] [pid 16817] [client 52.9.128.29:42158] mod_fcgid: stderr: PHP Fatal error: Uncaught Error: Call to undefined function get_header() in /var/www/clients/client1/web1/web/wp-content/themes/study-circle/index.php:13
[Tue Jan 21 09:15:26.128824 2020] [fcgid:warn] [pid 16817] [client 52.9.128.29:42158] mod_fcgid: stderr: Stack trace:
[Tue Jan 21 09:15:26.128832 2020] [fcgid:warn] [pid 16817] [client 52.9.128.29:42158] mod_fcgid: stderr: #0 {main}
[Tue Jan 21 09:15:26.128837 2020] [fcgid:warn] [pid 16817] [client 52.9.128.29:42158] mod_fcgid: stderr: thrown in /var/www/clients/client1/web1/web/wp-content/themes/study-circle/index.php on line 13
```
The index.php code looks normal to me...
```
<?php
/**
* The template for displaying home page.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package Study Circle
*/
get_header();
?>
<div class="container">
<div class="page_content">
<section class="site-main">
<div class="blog-post">
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post();
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content' );
endwhile;
// Previous/next post navigation.
the_posts_pagination();
else :
// If no content, include the "No posts found" template.
get_template_part( 'no-results', 'index' );
endif;
?>
</div><!-- blog-post -->
</section>
<?php get_sidebar();?>
<div class="clear"></div>
</div><!-- site-aligner -->
</div><!-- content -->
<?php get_footer(); ?>
```
And the `get_header` Function from wp-includes/general-template.php:
```
function get_header( $name = null ) {
/**
* Fires before the header template file is loaded.
*
* @since 2.1.0
* @since 2.8.0 $name parameter added.
*
* @param string|null $name Name of the specific header file to use. null for the default header.
*/
do_action( 'get_header', $name );
$templates = array();
$name = (string) $name;
if ( '' !== $name ) {
$templates[] = "header-{$name}.php";
}
$templates[] = 'header.php';
locate_template( $templates, true );
}
``` | In the end I could not solve this myself. I hired a freelancer who specialised in WP development. As it turned out, it was a plugin (OptimizePress 2) that was responsible for this problem, however, the issue remained even when that plugin was deactived. How this is possible, I don't know, and can't give any real technical details on.
Just wanted to report back. |
356,862 | <p>I need help with my WP installation.</p>
<p>I have a home server for tests with LAMP and WP. I have created three sites: <code>main.lan</code>, <code>test2.lan</code> and <code>pbtest.lan</code>.</p>
<p><code>pbtest.lan</code> was installed first, this is a multisite installation with subfolders. It worked perfect. Then I have added two new sites. I have access from another PC, so I have created necessary entries in hosts files on PC and server to have access with domain name. And at this moment problem occured. </p>
<p>Two new sites are working properly, when I put <code>main.lan</code> in the browser I have <code>main.lan</code> site opened. The same with <code>test2.lan</code>. But when I try to open <code>pbtest.lan</code> I see <code>main.lan</code> site. In address bar there is IP address of my server instead of domain name. For <code>main.lan</code> and <code>test2.lan</code> there is domain name in the bar. When I disable two new sites and <code>pbtest.lan</code> is the only one avaliable site it is opened properly.</p>
<p>This is part of <code>wp-config.php</code> file for <code>pbtest.lan</code> site:</p>
<pre class="lang-php prettyprint-override"><code> /*Multisite*/
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', '192.168.1.110');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
</code></pre>
<p><code>define('DOMAIN_CURRENT_SITE', '192.168.1.110');</code> I think this line redirects traffic to IP address, and first avaliable site is opened. In my case this is main.lan. When I replaced IP address with domain name pbtest.lan I get error conection with database.</p>
<p>I tried put the full path to the directory, but it didn't worked.</p>
<p>Help, what shell I change to have all sites work?</p>
<p>Thank you</p>
<p>English is not my native language, but I hope you will understand my problem :)</p>
| [
{
"answer_id": 356833,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Besides looking at your inbox for any messages that WP might send you (they don't always get sent), look at the error.log file in the site root and wp-admin folders. That will tell you where the error is.</p>\n\n<p>If it is a plugin, then rename that plugin's folder temporarily, then try the update again. You could also rename the entire plugin folder to temporarily disable all plugins. And you might consider reverting to one of the 'twenty' themes to do your update.</p>\n\n<p>Once you have updated WP (and updated your PHP version, which may also be the problem; contact your hosting place for instructions on that), you can move back to your old theme. Then make a new plugins folder, and move each plugin folder individually to the new plugins folder. After each move, check the admin page, and do the 'update' check. Repeat for each plugin. (And update your theme, if needed.)</p>\n\n<p>Your issue shows the importance of keeping WP - core, themes, and plugins - updated. Less problems that way. (And the importance of updating your PHP version.)</p>\n"
},
{
"answer_id": 358565,
"author": "rohrl77",
"author_id": 112790,
"author_profile": "https://wordpress.stackexchange.com/users/112790",
"pm_score": 1,
"selected": true,
"text": "<p>In the end I could not solve this myself. I hired a freelancer who specialised in WP development. As it turned out, it was a plugin (OptimizePress 2) that was responsible for this problem, however, the issue remained even when that plugin was deactived. How this is possible, I don't know, and can't give any real technical details on. </p>\n\n<p>Just wanted to report back.</p>\n"
}
] | 2020/01/21 | [
"https://wordpress.stackexchange.com/questions/356862",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181385/"
] | I need help with my WP installation.
I have a home server for tests with LAMP and WP. I have created three sites: `main.lan`, `test2.lan` and `pbtest.lan`.
`pbtest.lan` was installed first, this is a multisite installation with subfolders. It worked perfect. Then I have added two new sites. I have access from another PC, so I have created necessary entries in hosts files on PC and server to have access with domain name. And at this moment problem occured.
Two new sites are working properly, when I put `main.lan` in the browser I have `main.lan` site opened. The same with `test2.lan`. But when I try to open `pbtest.lan` I see `main.lan` site. In address bar there is IP address of my server instead of domain name. For `main.lan` and `test2.lan` there is domain name in the bar. When I disable two new sites and `pbtest.lan` is the only one avaliable site it is opened properly.
This is part of `wp-config.php` file for `pbtest.lan` site:
```php
/*Multisite*/
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', '192.168.1.110');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
```
`define('DOMAIN_CURRENT_SITE', '192.168.1.110');` I think this line redirects traffic to IP address, and first avaliable site is opened. In my case this is main.lan. When I replaced IP address with domain name pbtest.lan I get error conection with database.
I tried put the full path to the directory, but it didn't worked.
Help, what shell I change to have all sites work?
Thank you
English is not my native language, but I hope you will understand my problem :) | In the end I could not solve this myself. I hired a freelancer who specialised in WP development. As it turned out, it was a plugin (OptimizePress 2) that was responsible for this problem, however, the issue remained even when that plugin was deactived. How this is possible, I don't know, and can't give any real technical details on.
Just wanted to report back. |
356,949 | <p>On a page like taxonomy-product_cat.php - this function lists just the products for the called sub-category - bags:</p>
<pre><code>$args = array( 'post_type' => 'product', 'product_cat' => 'bags')
$loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post();
</code></pre>
<p>I can hardcode list all the sub-categories and then dynamically list the products. I want to dynamically create the subcategory list with the associated products listed with it - what is the best way to do this? I am thinking that if I make the 'product_cat' => dynamic - is a way to achieve this?</p>
| [
{
"answer_id": 356962,
"author": "CHEWX",
"author_id": 109779,
"author_profile": "https://wordpress.stackexchange.com/users/109779",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <code>get_queried_object()</code>, within that object you can get the <code>slug</code> or <code>id</code>.</p>\n"
},
{
"answer_id": 357063,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't be using <code>WP_Query</code> at all. The <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#the-loop-in-detail\" rel=\"nofollow noreferrer\">standard loop</a> will automatically display the correct posts.</p>\n\n<pre><code>while ( have_posts() ) : the_post();\n\nendwhile;\n</code></pre>\n"
}
] | 2020/01/22 | [
"https://wordpress.stackexchange.com/questions/356949",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14416/"
] | On a page like taxonomy-product\_cat.php - this function lists just the products for the called sub-category - bags:
```
$args = array( 'post_type' => 'product', 'product_cat' => 'bags')
$loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post();
```
I can hardcode list all the sub-categories and then dynamically list the products. I want to dynamically create the subcategory list with the associated products listed with it - what is the best way to do this? I am thinking that if I make the 'product\_cat' => dynamic - is a way to achieve this? | You shouldn't be using `WP_Query` at all. The [standard loop](https://developer.wordpress.org/themes/basics/the-loop/#the-loop-in-detail) will automatically display the correct posts.
```
while ( have_posts() ) : the_post();
endwhile;
``` |
356,950 | <p>Apparently, for some illogical reason, the developers decided that the only way to fetch posts in all languages, is to add <code>supress_filters=true</code> to the WP_Query (instead of having like say, a <code>language_code=all</code> option).</p>
<p>Anyways, I am in a situation where I need to fetch posts in all languages, but ALSO modify the WP_Query using filters. Is there a way to enforce that my filters are being added to the query, even though <code>supress_filters</code> is set to <code>false</code>?</p>
<p>This is the filter I need to add:</p>
<pre><code>add_filter( 'posts_where', function($where, $wp_query) {
global $wpdb;
if($search_term = $wp_query->get( 'custom_search' )){
$search_term = $wpdb->esc_like($search_term);
$search_term = ' \'%' . $search_term . '%\'';
$where .= ' AND (' . $wpdb->posts . '.post_title LIKE ' . $search_term . ' OR ' . $wpdb->posts . '.ID LIKE ' . $search_term . ' OR ' . $wpdb->posts . '.post_name LIKE ' . $search_term . ')';
}
return $where;
}, 10, 2 );
</code></pre>
<p>But it is removed after adding <code>supress_filters=true</code> (because I need to fetch posts in ALL languages)</p>
| [
{
"answer_id": 356962,
"author": "CHEWX",
"author_id": 109779,
"author_profile": "https://wordpress.stackexchange.com/users/109779",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <code>get_queried_object()</code>, within that object you can get the <code>slug</code> or <code>id</code>.</p>\n"
},
{
"answer_id": 357063,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't be using <code>WP_Query</code> at all. The <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#the-loop-in-detail\" rel=\"nofollow noreferrer\">standard loop</a> will automatically display the correct posts.</p>\n\n<pre><code>while ( have_posts() ) : the_post();\n\nendwhile;\n</code></pre>\n"
}
] | 2020/01/22 | [
"https://wordpress.stackexchange.com/questions/356950",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50042/"
] | Apparently, for some illogical reason, the developers decided that the only way to fetch posts in all languages, is to add `supress_filters=true` to the WP\_Query (instead of having like say, a `language_code=all` option).
Anyways, I am in a situation where I need to fetch posts in all languages, but ALSO modify the WP\_Query using filters. Is there a way to enforce that my filters are being added to the query, even though `supress_filters` is set to `false`?
This is the filter I need to add:
```
add_filter( 'posts_where', function($where, $wp_query) {
global $wpdb;
if($search_term = $wp_query->get( 'custom_search' )){
$search_term = $wpdb->esc_like($search_term);
$search_term = ' \'%' . $search_term . '%\'';
$where .= ' AND (' . $wpdb->posts . '.post_title LIKE ' . $search_term . ' OR ' . $wpdb->posts . '.ID LIKE ' . $search_term . ' OR ' . $wpdb->posts . '.post_name LIKE ' . $search_term . ')';
}
return $where;
}, 10, 2 );
```
But it is removed after adding `supress_filters=true` (because I need to fetch posts in ALL languages) | You shouldn't be using `WP_Query` at all. The [standard loop](https://developer.wordpress.org/themes/basics/the-loop/#the-loop-in-detail) will automatically display the correct posts.
```
while ( have_posts() ) : the_post();
endwhile;
``` |
356,963 | <p>I have a spreadsheet of information I'd like to publish online. I'm trying to find the easiest and best-looking way of doing this. The page will be informational and not intended to generate revenue so I'm hoping to be able to do this cheaply - WordPress seems like the best option.</p>
<p>I'd like to create a website to display my data in different ways. For example, one page would tabulate most of the data. From there, you could click on a heading and go to a page just for that entry, with additional information. Another page would tabulate data only relevant to that day. And so on. </p>
<p>It's not really a blog-style page. Is there a good way of doing this with WordPress?</p>
| [
{
"answer_id": 356962,
"author": "CHEWX",
"author_id": 109779,
"author_profile": "https://wordpress.stackexchange.com/users/109779",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <code>get_queried_object()</code>, within that object you can get the <code>slug</code> or <code>id</code>.</p>\n"
},
{
"answer_id": 357063,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't be using <code>WP_Query</code> at all. The <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#the-loop-in-detail\" rel=\"nofollow noreferrer\">standard loop</a> will automatically display the correct posts.</p>\n\n<pre><code>while ( have_posts() ) : the_post();\n\nendwhile;\n</code></pre>\n"
}
] | 2020/01/22 | [
"https://wordpress.stackexchange.com/questions/356963",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181457/"
] | I have a spreadsheet of information I'd like to publish online. I'm trying to find the easiest and best-looking way of doing this. The page will be informational and not intended to generate revenue so I'm hoping to be able to do this cheaply - WordPress seems like the best option.
I'd like to create a website to display my data in different ways. For example, one page would tabulate most of the data. From there, you could click on a heading and go to a page just for that entry, with additional information. Another page would tabulate data only relevant to that day. And so on.
It's not really a blog-style page. Is there a good way of doing this with WordPress? | You shouldn't be using `WP_Query` at all. The [standard loop](https://developer.wordpress.org/themes/basics/the-loop/#the-loop-in-detail) will automatically display the correct posts.
```
while ( have_posts() ) : the_post();
endwhile;
``` |
356,972 | <p>I using the plugin from <a href="https://github.com/birgire/wpse-playlist" rel="nofollow noreferrer">https://github.com/birgire/wpse-playlist</a> so far I really enjoy it, but I hope anyone can help me to change the code little bit, Like:
The original code:</p>
<pre><code>[_playlist]
[_track title="Ain't Misbehavin'" src="//s.w.org/images/core/3.9/AintMisbehavin.mp3"]
[_track title="Buddy Bolden's Blues" src="//s.w.org/images/core/3.9/JellyRollMorton-BuddyBoldensBlues.mp3"]
[/_playlist]
</code></pre>
<p>I want to change it to:</p>
<pre><code>[_playlist]
http://s.w.org/images/core/3.9/AintMisbehavin.mp3
http://s.w.org/images/core/3.9/JellyRollMorton-BuddyBoldensBlues.mp3
[/_playlist]
</code></pre>
| [
{
"answer_id": 356974,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 2,
"selected": true,
"text": "<p>At first glance you just need to change <a href=\"https://github.com/birgire/wpse-playlist/blob/0.0.9/php/class.playlist.php#L153\" rel=\"nofollow noreferrer\">get_tracks_from_content</a>. Rather than running $content through do_shortcodes,</p>\n\n<ul>\n<li>split it by linebreaks (or whitespace?) and discard empty lines, or anything that isn't an URL\n\n<ul>\n<li>probably make the strip_tags call at this point, on each value you have left</li>\n</ul></li>\n<li>pass the URLs into track_shortcode as <code>[ \"src\" => $url ]</code>, plus any other common metadata you want to set here</li>\n<li>concatenate the results to make a new $content</li>\n<li>continue with the <code>// Replace last comma</code> code.</li>\n</ul>\n"
},
{
"answer_id": 357024,
"author": "thejack99",
"author_id": 181459,
"author_profile": "https://wordpress.stackexchange.com/users/181459",
"pm_score": 0,
"selected": false,
"text": "<p>I try out but had noluck, maybe I misunderstanding somewhere.\nHere is the WPSE function file, Please show me where I need to edit:</p>\n\n<pre><code><?php\n\nnamespace birgire;\n\n/**\n * Class Playlist\n */\n\nclass Playlist\n{\n protected $type = '';\n protected $types = array( 'audio', 'video' );\n protected $instance = 0;\n\n /**\n * Init - Register shortcodes\n */\n\n public function init()\n {\n add_shortcode( '_playlist', array( $this, 'playlist_shortcode' ) );\n add_shortcode( '_track', array( $this, 'track_shortcode' ) );\n\n // Deprecated:\n add_shortcode( 'wpse_playlist', array( $this, 'playlist_shortcode' ) );\n add_shortcode( 'wpse_trac', array( $this, 'track_shortcode' ) );\n }\n\n\n /**\n * Callback for the [_playlist] shortcode\n *\n * @uses wp_validate_boolean() from WordPress 4.0\n */\n\n public function playlist_shortcode( $atts = array(), $content = '' ) \n { \n global $content_width; // Theme dependent content width\n $this->instance++; // Counter to activate the 'wp_playlist_scripts' action only once\n\n $atts = shortcode_atts( \n array(\n 'type' => 'audio',\n 'style' => 'light',\n 'tracklist' => 'true',\n 'tracknumbers' => 'true',\n 'images' => 'true', // Audio related\n 'artists' => 'true', // Audio related\n 'current' => 'true',\n 'autoplay' => 'false',\n 'class' => 'wpse-playlist',\n 'width' => '',\n 'height' => '',\n 'outer' => '20',\n 'default_width' => '640',\n 'default_height' => '380',\n ), \n $atts, \n 'wpse_playlist_shortcode' \n );\n\n // Autoplay:\n $autoplay = wp_validate_boolean( $atts['autoplay'] ) ? 'autoplay=\"yes\"' : '';\n\n // Nested shortcode support:\n $this->type = ( in_array( $atts['type'], $this->types, TRUE ) ) ? esc_attr( $atts['type'] ) : 'audio';\n\n // Enqueue default scripts and styles for the playlist.\n ( 1 === $this->instance ) && do_action( 'wp_playlist_scripts', esc_attr( $atts['type'] ), esc_attr( $atts['style'] ) );\n\n //----------\n // Height & Width - Adjusted from the WordPress core\n //----------\n\n $width = esc_attr( $atts['width'] ); \n if( empty( $width ) )\n $width = empty( $content_width ) \n ? intval( $atts['default_width'] ) \n : ( $content_width - intval( $atts['outer'] ) );\n\n $height = esc_attr( $atts['height'] ); \n if( empty( $height ) && intval( $atts['default_height'] ) > 0 )\n $height = empty( $content_width ) \n ? intval( $atts['default_height'] )\n : round( ( intval( $atts['default_height'] ) * $width ) / intval( $atts['default_width'] ) );\n\n //----------\n // Output\n //----------\n\n $html = '';\n\n // Start div container:\n $html .= sprintf( '<div class=\"wp-playlist wp-%s-playlist wp-playlist-%s ' . esc_attr( $atts['class'] ) . '\">', \n $this->type, \n esc_attr( $atts['style'] )\n );\n\n // Current audio item:\n if( $atts['current'] && 'audio' === $this->type )\n {\n $html .= '<div class=\"wp-playlist-current-item\"></div>'; \n }\n\n // Video player: \n if( 'video' === $this->type )\n {\n $html .= sprintf( '<video controls=\"controls\" ' . $autoplay . ' preload=\"none\" width=\"%s\" height=\"%s\"></video>',\n $width,\n $height\n );\n }\n // Audio player: \n else\n {\n $html .= sprintf( '<audio controls=\"controls\" ' . $autoplay . ' preload=\"none\" width=\"%s\" style=\"visibility: hidden\"></audio>', \n $width \n );\n }\n\n // Next/Previous:\n $html .= '<div class=\"wp-playlist-next\"></div><div class=\"wp-playlist-prev\"></div>';\n\n // JSON \n $html .= sprintf( '\n <script class=\"wp-playlist-script\" type=\"application/json\">{\n \"type\":\"%s\",\n \"tracklist\":%s,\n \"tracknumbers\":%s,\n \"images\":%s,\n \"artists\":%s,\n \"tracks\":[%s]\n }</script>', \n esc_attr( $atts['type'] ), \n wp_validate_boolean( $atts['tracklist'] ) ? 'true' : 'false', \n wp_validate_boolean( $atts['tracknumbers'] ) ? 'true' : 'false', \n wp_validate_boolean( $atts['images'] ) ? 'true' : 'false',\n wp_validate_boolean( $atts['artists'] ) ? 'true' : 'false',\n $this->get_tracks_from_content( $content )\n );\n\n // Close div container:\n $html .= '</div>';\n\n return $html;\n }\n\n\n /**\n * Get tracks from the [_playlist] shortcode content string\n */\n\n private function get_tracks_from_content( $content )\n {\n // Get tracs:\n $content = strip_tags( nl2br( do_shortcode( $content ) ) );\n\n // Replace last comma:\n if( FALSE !== ( $pos = strrpos( $content, ',' ) ) )\n {\n $content = substr_replace( $content, '', $pos, 1 );\n }\n\n return $content;\n }\n\n\n /**\n * Callback for the [_track] shortcode\n */\n\n public function track_shortcode( $atts = array(), $content = '' ) \n { \n\n $atts = shortcode_atts( \n array(\n 'src' => '',\n 'type' => ( 'video' === $this->type ) ? 'video/mp4' : 'audio/mpeg',\n 'title' => '',\n 'caption' => '',\n 'description' => '',\n 'image_src' => sprintf( '%s/wp-includes/images/media/%s.png', get_site_url(), $this->type ),\n 'image_width' => '48',\n 'image_height' => '64',\n 'thumb_src' => sprintf( '%s/wp-includes/images/media/%s.png', get_site_url(), $this->type ),\n 'thumb_width' => '48',\n 'thumb_height' => '64',\n 'meta_artist' => '',\n 'meta_album' => '',\n 'meta_genre' => '',\n 'meta_length_formatted' => '',\n 'dimensions_original_width' => '300',\n 'dimensions_original_height' => '200',\n 'dimensions_resized_width' => '600',\n 'dimensions_resized_height' => '400',\n ), \n $atts, \n 'wpse_track_shortcode' \n );\n\n //----------\n // Data output:\n //----------\n $data['src'] = esc_url( $atts['src'] );\n $data['title'] = sanitize_text_field( $atts['title'] );\n $data['type'] = sanitize_text_field( $atts['type'] );\n $data['caption'] = sanitize_text_field( $atts['caption'] );\n $data['description'] = sanitize_text_field( $atts['description'] );\n $data['image']['src'] = esc_url( $atts['image_src'] );\n $data['image']['width'] = intval( $atts['image_width'] );\n $data['image']['height'] = intval( $atts['image_height'] );\n $data['thumb']['src'] = esc_url( $atts['thumb_src'] );\n $data['thumb']['width'] = intval( $atts['thumb_width'] );\n $data['thumb']['height'] = intval( $atts['thumb_height'] );\n $data['meta']['length_formatted'] = sanitize_text_field( $atts['meta_length_formatted'] );\n\n // Video related:\n if( 'video' === $this->type ) \n {\n $data['dimensions']['original']['width'] = sanitize_text_field( $atts['dimensions_original_width'] );\n $data['dimensions']['original']['height'] = sanitize_text_field( $atts['dimensions_original_height'] );\n $data['dimensions']['resized']['width'] = sanitize_text_field( $atts['dimensions_resized_width'] );\n $data['dimensions']['resized']['height'] = sanitize_text_field( $atts['dimensions_resized_height'] );\n\n // Audio related:\n } else {\n $data['meta']['artist'] = sanitize_text_field( $atts['meta_artist'] );\n $data['meta']['album'] = sanitize_text_field( $atts['meta_album'] );\n $data['meta']['genre'] = sanitize_text_field( $atts['meta_genre'] );\n }\n\n return json_encode( $data ) . ','; \n }\n\n} // end class\n</code></pre>\n"
}
] | 2020/01/22 | [
"https://wordpress.stackexchange.com/questions/356972",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181459/"
] | I using the plugin from <https://github.com/birgire/wpse-playlist> so far I really enjoy it, but I hope anyone can help me to change the code little bit, Like:
The original code:
```
[_playlist]
[_track title="Ain't Misbehavin'" src="//s.w.org/images/core/3.9/AintMisbehavin.mp3"]
[_track title="Buddy Bolden's Blues" src="//s.w.org/images/core/3.9/JellyRollMorton-BuddyBoldensBlues.mp3"]
[/_playlist]
```
I want to change it to:
```
[_playlist]
http://s.w.org/images/core/3.9/AintMisbehavin.mp3
http://s.w.org/images/core/3.9/JellyRollMorton-BuddyBoldensBlues.mp3
[/_playlist]
``` | At first glance you just need to change [get\_tracks\_from\_content](https://github.com/birgire/wpse-playlist/blob/0.0.9/php/class.playlist.php#L153). Rather than running $content through do\_shortcodes,
* split it by linebreaks (or whitespace?) and discard empty lines, or anything that isn't an URL
+ probably make the strip\_tags call at this point, on each value you have left
* pass the URLs into track\_shortcode as `[ "src" => $url ]`, plus any other common metadata you want to set here
* concatenate the results to make a new $content
* continue with the `// Replace last comma` code. |
356,976 | <p>So I'm having an issue where I'm getting a 'Undefined function' response and I can't seem to figure out why and how to target it.</p>
<p><strong>Relative path to the shortcode file</strong>: htdocs/wp-content/mu-plugins/s/shortcodes/profile.php
<a href="https://i.stack.imgur.com/aXSLT.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aXSLT.gif" alt="enter image description here"></a></p>
<p><strong>Relative path to the profile card</strong>: htdocs/wp-content/mu-plugins/s/templates/people-card.php<br>
- (This is where I have some HTML)</p>
<hr>
<p>What I'd like to achieve:</p>
<ul>
<li>Apply the shortcode to the page then have the shortcode function call the profile-card.php page and grab all the content within and display it.</li>
</ul>
<p>So are the very end, the shortcode will show the 'profile-card.php' page.</p>
<p><strong>The code I have inside shortcodes/profile.php</strong>:</p>
<pre><code>function clearline_func() {
test();
}
add_shortcode('test', 'clearline_func');
</code></pre>
<p>I'm getting a <code>Fatal error: Uncaught Error: Call to undefined function test()</code> error.</p>
| [
{
"answer_id": 356974,
"author": "Rup",
"author_id": 3276,
"author_profile": "https://wordpress.stackexchange.com/users/3276",
"pm_score": 2,
"selected": true,
"text": "<p>At first glance you just need to change <a href=\"https://github.com/birgire/wpse-playlist/blob/0.0.9/php/class.playlist.php#L153\" rel=\"nofollow noreferrer\">get_tracks_from_content</a>. Rather than running $content through do_shortcodes,</p>\n\n<ul>\n<li>split it by linebreaks (or whitespace?) and discard empty lines, or anything that isn't an URL\n\n<ul>\n<li>probably make the strip_tags call at this point, on each value you have left</li>\n</ul></li>\n<li>pass the URLs into track_shortcode as <code>[ \"src\" => $url ]</code>, plus any other common metadata you want to set here</li>\n<li>concatenate the results to make a new $content</li>\n<li>continue with the <code>// Replace last comma</code> code.</li>\n</ul>\n"
},
{
"answer_id": 357024,
"author": "thejack99",
"author_id": 181459,
"author_profile": "https://wordpress.stackexchange.com/users/181459",
"pm_score": 0,
"selected": false,
"text": "<p>I try out but had noluck, maybe I misunderstanding somewhere.\nHere is the WPSE function file, Please show me where I need to edit:</p>\n\n<pre><code><?php\n\nnamespace birgire;\n\n/**\n * Class Playlist\n */\n\nclass Playlist\n{\n protected $type = '';\n protected $types = array( 'audio', 'video' );\n protected $instance = 0;\n\n /**\n * Init - Register shortcodes\n */\n\n public function init()\n {\n add_shortcode( '_playlist', array( $this, 'playlist_shortcode' ) );\n add_shortcode( '_track', array( $this, 'track_shortcode' ) );\n\n // Deprecated:\n add_shortcode( 'wpse_playlist', array( $this, 'playlist_shortcode' ) );\n add_shortcode( 'wpse_trac', array( $this, 'track_shortcode' ) );\n }\n\n\n /**\n * Callback for the [_playlist] shortcode\n *\n * @uses wp_validate_boolean() from WordPress 4.0\n */\n\n public function playlist_shortcode( $atts = array(), $content = '' ) \n { \n global $content_width; // Theme dependent content width\n $this->instance++; // Counter to activate the 'wp_playlist_scripts' action only once\n\n $atts = shortcode_atts( \n array(\n 'type' => 'audio',\n 'style' => 'light',\n 'tracklist' => 'true',\n 'tracknumbers' => 'true',\n 'images' => 'true', // Audio related\n 'artists' => 'true', // Audio related\n 'current' => 'true',\n 'autoplay' => 'false',\n 'class' => 'wpse-playlist',\n 'width' => '',\n 'height' => '',\n 'outer' => '20',\n 'default_width' => '640',\n 'default_height' => '380',\n ), \n $atts, \n 'wpse_playlist_shortcode' \n );\n\n // Autoplay:\n $autoplay = wp_validate_boolean( $atts['autoplay'] ) ? 'autoplay=\"yes\"' : '';\n\n // Nested shortcode support:\n $this->type = ( in_array( $atts['type'], $this->types, TRUE ) ) ? esc_attr( $atts['type'] ) : 'audio';\n\n // Enqueue default scripts and styles for the playlist.\n ( 1 === $this->instance ) && do_action( 'wp_playlist_scripts', esc_attr( $atts['type'] ), esc_attr( $atts['style'] ) );\n\n //----------\n // Height & Width - Adjusted from the WordPress core\n //----------\n\n $width = esc_attr( $atts['width'] ); \n if( empty( $width ) )\n $width = empty( $content_width ) \n ? intval( $atts['default_width'] ) \n : ( $content_width - intval( $atts['outer'] ) );\n\n $height = esc_attr( $atts['height'] ); \n if( empty( $height ) && intval( $atts['default_height'] ) > 0 )\n $height = empty( $content_width ) \n ? intval( $atts['default_height'] )\n : round( ( intval( $atts['default_height'] ) * $width ) / intval( $atts['default_width'] ) );\n\n //----------\n // Output\n //----------\n\n $html = '';\n\n // Start div container:\n $html .= sprintf( '<div class=\"wp-playlist wp-%s-playlist wp-playlist-%s ' . esc_attr( $atts['class'] ) . '\">', \n $this->type, \n esc_attr( $atts['style'] )\n );\n\n // Current audio item:\n if( $atts['current'] && 'audio' === $this->type )\n {\n $html .= '<div class=\"wp-playlist-current-item\"></div>'; \n }\n\n // Video player: \n if( 'video' === $this->type )\n {\n $html .= sprintf( '<video controls=\"controls\" ' . $autoplay . ' preload=\"none\" width=\"%s\" height=\"%s\"></video>',\n $width,\n $height\n );\n }\n // Audio player: \n else\n {\n $html .= sprintf( '<audio controls=\"controls\" ' . $autoplay . ' preload=\"none\" width=\"%s\" style=\"visibility: hidden\"></audio>', \n $width \n );\n }\n\n // Next/Previous:\n $html .= '<div class=\"wp-playlist-next\"></div><div class=\"wp-playlist-prev\"></div>';\n\n // JSON \n $html .= sprintf( '\n <script class=\"wp-playlist-script\" type=\"application/json\">{\n \"type\":\"%s\",\n \"tracklist\":%s,\n \"tracknumbers\":%s,\n \"images\":%s,\n \"artists\":%s,\n \"tracks\":[%s]\n }</script>', \n esc_attr( $atts['type'] ), \n wp_validate_boolean( $atts['tracklist'] ) ? 'true' : 'false', \n wp_validate_boolean( $atts['tracknumbers'] ) ? 'true' : 'false', \n wp_validate_boolean( $atts['images'] ) ? 'true' : 'false',\n wp_validate_boolean( $atts['artists'] ) ? 'true' : 'false',\n $this->get_tracks_from_content( $content )\n );\n\n // Close div container:\n $html .= '</div>';\n\n return $html;\n }\n\n\n /**\n * Get tracks from the [_playlist] shortcode content string\n */\n\n private function get_tracks_from_content( $content )\n {\n // Get tracs:\n $content = strip_tags( nl2br( do_shortcode( $content ) ) );\n\n // Replace last comma:\n if( FALSE !== ( $pos = strrpos( $content, ',' ) ) )\n {\n $content = substr_replace( $content, '', $pos, 1 );\n }\n\n return $content;\n }\n\n\n /**\n * Callback for the [_track] shortcode\n */\n\n public function track_shortcode( $atts = array(), $content = '' ) \n { \n\n $atts = shortcode_atts( \n array(\n 'src' => '',\n 'type' => ( 'video' === $this->type ) ? 'video/mp4' : 'audio/mpeg',\n 'title' => '',\n 'caption' => '',\n 'description' => '',\n 'image_src' => sprintf( '%s/wp-includes/images/media/%s.png', get_site_url(), $this->type ),\n 'image_width' => '48',\n 'image_height' => '64',\n 'thumb_src' => sprintf( '%s/wp-includes/images/media/%s.png', get_site_url(), $this->type ),\n 'thumb_width' => '48',\n 'thumb_height' => '64',\n 'meta_artist' => '',\n 'meta_album' => '',\n 'meta_genre' => '',\n 'meta_length_formatted' => '',\n 'dimensions_original_width' => '300',\n 'dimensions_original_height' => '200',\n 'dimensions_resized_width' => '600',\n 'dimensions_resized_height' => '400',\n ), \n $atts, \n 'wpse_track_shortcode' \n );\n\n //----------\n // Data output:\n //----------\n $data['src'] = esc_url( $atts['src'] );\n $data['title'] = sanitize_text_field( $atts['title'] );\n $data['type'] = sanitize_text_field( $atts['type'] );\n $data['caption'] = sanitize_text_field( $atts['caption'] );\n $data['description'] = sanitize_text_field( $atts['description'] );\n $data['image']['src'] = esc_url( $atts['image_src'] );\n $data['image']['width'] = intval( $atts['image_width'] );\n $data['image']['height'] = intval( $atts['image_height'] );\n $data['thumb']['src'] = esc_url( $atts['thumb_src'] );\n $data['thumb']['width'] = intval( $atts['thumb_width'] );\n $data['thumb']['height'] = intval( $atts['thumb_height'] );\n $data['meta']['length_formatted'] = sanitize_text_field( $atts['meta_length_formatted'] );\n\n // Video related:\n if( 'video' === $this->type ) \n {\n $data['dimensions']['original']['width'] = sanitize_text_field( $atts['dimensions_original_width'] );\n $data['dimensions']['original']['height'] = sanitize_text_field( $atts['dimensions_original_height'] );\n $data['dimensions']['resized']['width'] = sanitize_text_field( $atts['dimensions_resized_width'] );\n $data['dimensions']['resized']['height'] = sanitize_text_field( $atts['dimensions_resized_height'] );\n\n // Audio related:\n } else {\n $data['meta']['artist'] = sanitize_text_field( $atts['meta_artist'] );\n $data['meta']['album'] = sanitize_text_field( $atts['meta_album'] );\n $data['meta']['genre'] = sanitize_text_field( $atts['meta_genre'] );\n }\n\n return json_encode( $data ) . ','; \n }\n\n} // end class\n</code></pre>\n"
}
] | 2020/01/23 | [
"https://wordpress.stackexchange.com/questions/356976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | So I'm having an issue where I'm getting a 'Undefined function' response and I can't seem to figure out why and how to target it.
**Relative path to the shortcode file**: htdocs/wp-content/mu-plugins/s/shortcodes/profile.php
[](https://i.stack.imgur.com/aXSLT.gif)
**Relative path to the profile card**: htdocs/wp-content/mu-plugins/s/templates/people-card.php
- (This is where I have some HTML)
---
What I'd like to achieve:
* Apply the shortcode to the page then have the shortcode function call the profile-card.php page and grab all the content within and display it.
So are the very end, the shortcode will show the 'profile-card.php' page.
**The code I have inside shortcodes/profile.php**:
```
function clearline_func() {
test();
}
add_shortcode('test', 'clearline_func');
```
I'm getting a `Fatal error: Uncaught Error: Call to undefined function test()` error. | At first glance you just need to change [get\_tracks\_from\_content](https://github.com/birgire/wpse-playlist/blob/0.0.9/php/class.playlist.php#L153). Rather than running $content through do\_shortcodes,
* split it by linebreaks (or whitespace?) and discard empty lines, or anything that isn't an URL
+ probably make the strip\_tags call at this point, on each value you have left
* pass the URLs into track\_shortcode as `[ "src" => $url ]`, plus any other common metadata you want to set here
* concatenate the results to make a new $content
* continue with the `// Replace last comma` code. |
356,985 | <p>I want while loop to show three posts on first section and the remaining in another section.i am very new to wordpress ,and not having much practical knowledge in php.any help would be very much appreciable.</p>
<p>here is my index.php code:</p>
<pre><code> <!-- first section starting -->
<section class="main_section" id="masc">
<div class="container cardbox_1">
<div class="row cardbox_horizontal d-flex justify-content-center ">
<!-- while looping-section starting -->
<?php
$post_args = array( 'post_type' => 'Student Form', 'posts_per_page' => 6 );
$post_query = new WP_Query( $post_args );
if ( $post_query->have_posts() ) :
while ( $post_query->have_posts() ) : $post_query->the_post(); ?>
<?php if ( $post_query->the_posts() >= 3 ) : ?>
<!-- while loop -->
<div class=" col-md-4 cards">
<div class="card card_1">
<h3 class="h3 card_head text-uppercase">
<?php the_title(); ?>
</h3>
<div class="center_image d-flex justify-content-center">
<a rel="external" href="<php? the_permalink()?>">
<img class="image_head" src="<?php echo get_the_post_thumbnail_url(); ?>" alt="">
</a>
</div>
<div class="para_head"><?php the_content(); ?> </div>
<div class=" d-flex justify-content-end">
<a href="#" class="btn btn-primary">VIEW MORE</a>
</div>
<div>
</div>
<!-- while loop-->
<?php wp_reset_postdata(); ?>
<?php endwhile; // ending while loop ?>
<?php else: ?>
<p><?php _e( 'Sorry, no Students matched your criteria.' ); ?></p>
<?php endif; // ending condition ?>
<!-- while section ending -->
</div>
</div>
</div>
</section>
<!-- while section ending -->
<!-- middle section-(should not loop -this considered a border to top and bottom sections)ending -->
<section id="babg">
<div class="container">
<div class="row ">
<div class="col-md-12">
<hr class="this bbg">
</div>
</div>
</div>
</section>
<!-- middle section ending -->
<!-- here the same code again (this is faulty-i need the below post as numbered 4 )-->
<section class="main_section" id="masc">
<div class="container cardbox_1">
<div class="row cardbox_horizontal d-flex justify-content-center ">
<?php
$post_args = array( 'post_type' => 'Student Form', 'posts_per_page' => 3 );
$post_query = new WP_Query( $post_args );
if ( $post_query->have_posts() ) :
while ( $post_query->have_posts() ) : $post_query->the_post(); ?>
<div class=" col-md-4 cards">
<div class="card card_1">
<h3 class="h3 card_head text-uppercase">
<?php the_title(); ?>
</h3>
<div class="center_image d-flex justify-content-center">
<a rel="external" href="<php? the_permalink()?>">
<img class="image_head" src="<?php echo get_the_post_thumbnail_url(); ?>" alt="">
</a>
</div>
<div class="para_head"><?php the_content(); ?> </div>
<div class=" d-flex justify-content-end">
<a href="#" class="btn btn-primary">VIEW MORE</a>
</div>
</div>
</div>
<?php wp_reset_postdata(); ?>
<?php endwhile; // ending while loop ?>
<?php else: ?>
<p><?php _e( 'Sorry, no Students matched your criteria.' ); ?></p>
<?php endif; // ending condition ?>
</div>
</div>
</section>
<!-- pardon me for funny class names and my bad terminology -->
</code></pre>
| [
{
"answer_id": 356989,
"author": "Nayan Chowdhury",
"author_id": 181381,
"author_profile": "https://wordpress.stackexchange.com/users/181381",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to show 3 posts in a list, you can follow this pattern:</p>\n\n<pre><code><?php\n\n$args = array(\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'orderby' => 'date', \n 'order' => 'DSC',\n 'posts_per_page' => 3\n );\n$post_query = new WP_Query($args);\n\nif($post_query->have_posts()): while($post_query->have_posts()):$post_query->the_post();\n?>\n <div>\n <h1> <?php the_title(); ?> </h1>\n <?php the_excerpt(); ?>\n </div>\n<?php\nendwhile;\nendif;\n?>\n</code></pre>\n\n<p>Now you want to show rest of the posts in another section but want to exclude the first 3 posts, use offset. Here is the example:</p>\n\n<pre><code><?php\n\n$args = array(\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'orderby' => 'date', \n 'order' => 'DSC',\n 'posts_per_page' => -1, // will show unlimited posts\n 'offset' => 3\n );\n$post_query = new WP_Query($args);\n\nif($post_query->have_posts()): while($post_query->have_posts()):$post_query->the_post();\n?>\n <div>\n <h1> <?php the_title(); ?> </h1>\n <?php the_excerpt(); ?>\n </div>\n<?php\nendwhile;\nendif;\n?>\n</code></pre>\n\n<p>You need to edit the code according to your need. Hope this will help you.</p>\n"
},
{
"answer_id": 356991,
"author": "Tim Elsass",
"author_id": 80375,
"author_profile": "https://wordpress.stackexchange.com/users/80375",
"pm_score": 1,
"selected": true,
"text": "<p>What you are looking for is PHP's <a href=\"https://www.php.net/manual/en/language.operators.arithmetic.php\" rel=\"nofollow noreferrer\">modulo</a> operator and adjust markup as necessary:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n $i = 0;\n $did_hr = false;\n $post_args = array( 'post_type' => 'Student Form', 'posts_per_page' => 6 );\n $post_query = new WP_Query( $post_args ); \n\n\nif ( $post_query->have_posts() ) : \n\nwhile ( $post_query->have_posts() ) : $post_query->the_post(); ?>\n <?php if ( $i % 3 == 0 ) : ?>\n <section class=\"main_section\" id=\"masc\">\n <div class=\"container cardbox_1\">\n <div class=\"row cardbox_horizontal d-flex justify-content-center\">\n <?php endif; ?>\n <!-- while loop -->\n <div class=\" col-md-4 cards\">\n <div class=\"card card_1\">\n <h3 class=\"h3 card_head text-uppercase\">\n <?php the_title(); ?>\n </h3>\n <div class=\"center_image d-flex justify-content-center\">\n <a rel=\"external\" href=\"<?php the_permalink()?>\">\n <img class=\"image_head\" src=\"<?php echo get_the_post_thumbnail_url(); ?>\" alt=\"\">\n </a>\n </div>\n <div class=\"para_head\">\n <?php the_content(); ?>\n </div>\n <div class=\" d-flex justify-content-end\">\n <a href=\"#\" class=\"btn btn-primary\">VIEW MORE</a>\n </div>\n </div>\n </div>\n <?php $i++; if ( $i != 0 && $i % 3 == 0 ) : ?> \n </div>\n </div>\n </section>\n <?php if ( ! $did_hr ) : $did_hr = true; ?>\n <!-- middle section-(should not loop -this considered a border to top and bottom sections)ending -->\n <section id=\"babg\">\n <div class=\"container\">\n <div class=\"row \">\n <div class=\"col-md-12\">\n <hr class=\"this bbg\">\n </div>\n </div>\n </div>\n </section>\n <?php endif; ?>\n <!-- middle section ending -->\n <?php endif; ?><!-- while loop-->\n\n<?php endwhile; // ending while loop ?> \n<?php else: ?>\n <p><?php _e( 'Sorry, no Students matched your criteria.' ); ?></p>\n<?php endif; // ending condition ?>\n</code></pre>\n"
}
] | 2020/01/23 | [
"https://wordpress.stackexchange.com/questions/356985",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181471/"
] | I want while loop to show three posts on first section and the remaining in another section.i am very new to wordpress ,and not having much practical knowledge in php.any help would be very much appreciable.
here is my index.php code:
```
<!-- first section starting -->
<section class="main_section" id="masc">
<div class="container cardbox_1">
<div class="row cardbox_horizontal d-flex justify-content-center ">
<!-- while looping-section starting -->
<?php
$post_args = array( 'post_type' => 'Student Form', 'posts_per_page' => 6 );
$post_query = new WP_Query( $post_args );
if ( $post_query->have_posts() ) :
while ( $post_query->have_posts() ) : $post_query->the_post(); ?>
<?php if ( $post_query->the_posts() >= 3 ) : ?>
<!-- while loop -->
<div class=" col-md-4 cards">
<div class="card card_1">
<h3 class="h3 card_head text-uppercase">
<?php the_title(); ?>
</h3>
<div class="center_image d-flex justify-content-center">
<a rel="external" href="<php? the_permalink()?>">
<img class="image_head" src="<?php echo get_the_post_thumbnail_url(); ?>" alt="">
</a>
</div>
<div class="para_head"><?php the_content(); ?> </div>
<div class=" d-flex justify-content-end">
<a href="#" class="btn btn-primary">VIEW MORE</a>
</div>
<div>
</div>
<!-- while loop-->
<?php wp_reset_postdata(); ?>
<?php endwhile; // ending while loop ?>
<?php else: ?>
<p><?php _e( 'Sorry, no Students matched your criteria.' ); ?></p>
<?php endif; // ending condition ?>
<!-- while section ending -->
</div>
</div>
</div>
</section>
<!-- while section ending -->
<!-- middle section-(should not loop -this considered a border to top and bottom sections)ending -->
<section id="babg">
<div class="container">
<div class="row ">
<div class="col-md-12">
<hr class="this bbg">
</div>
</div>
</div>
</section>
<!-- middle section ending -->
<!-- here the same code again (this is faulty-i need the below post as numbered 4 )-->
<section class="main_section" id="masc">
<div class="container cardbox_1">
<div class="row cardbox_horizontal d-flex justify-content-center ">
<?php
$post_args = array( 'post_type' => 'Student Form', 'posts_per_page' => 3 );
$post_query = new WP_Query( $post_args );
if ( $post_query->have_posts() ) :
while ( $post_query->have_posts() ) : $post_query->the_post(); ?>
<div class=" col-md-4 cards">
<div class="card card_1">
<h3 class="h3 card_head text-uppercase">
<?php the_title(); ?>
</h3>
<div class="center_image d-flex justify-content-center">
<a rel="external" href="<php? the_permalink()?>">
<img class="image_head" src="<?php echo get_the_post_thumbnail_url(); ?>" alt="">
</a>
</div>
<div class="para_head"><?php the_content(); ?> </div>
<div class=" d-flex justify-content-end">
<a href="#" class="btn btn-primary">VIEW MORE</a>
</div>
</div>
</div>
<?php wp_reset_postdata(); ?>
<?php endwhile; // ending while loop ?>
<?php else: ?>
<p><?php _e( 'Sorry, no Students matched your criteria.' ); ?></p>
<?php endif; // ending condition ?>
</div>
</div>
</section>
<!-- pardon me for funny class names and my bad terminology -->
``` | What you are looking for is PHP's [modulo](https://www.php.net/manual/en/language.operators.arithmetic.php) operator and adjust markup as necessary:
```php
<?php
$i = 0;
$did_hr = false;
$post_args = array( 'post_type' => 'Student Form', 'posts_per_page' => 6 );
$post_query = new WP_Query( $post_args );
if ( $post_query->have_posts() ) :
while ( $post_query->have_posts() ) : $post_query->the_post(); ?>
<?php if ( $i % 3 == 0 ) : ?>
<section class="main_section" id="masc">
<div class="container cardbox_1">
<div class="row cardbox_horizontal d-flex justify-content-center">
<?php endif; ?>
<!-- while loop -->
<div class=" col-md-4 cards">
<div class="card card_1">
<h3 class="h3 card_head text-uppercase">
<?php the_title(); ?>
</h3>
<div class="center_image d-flex justify-content-center">
<a rel="external" href="<?php the_permalink()?>">
<img class="image_head" src="<?php echo get_the_post_thumbnail_url(); ?>" alt="">
</a>
</div>
<div class="para_head">
<?php the_content(); ?>
</div>
<div class=" d-flex justify-content-end">
<a href="#" class="btn btn-primary">VIEW MORE</a>
</div>
</div>
</div>
<?php $i++; if ( $i != 0 && $i % 3 == 0 ) : ?>
</div>
</div>
</section>
<?php if ( ! $did_hr ) : $did_hr = true; ?>
<!-- middle section-(should not loop -this considered a border to top and bottom sections)ending -->
<section id="babg">
<div class="container">
<div class="row ">
<div class="col-md-12">
<hr class="this bbg">
</div>
</div>
</div>
</section>
<?php endif; ?>
<!-- middle section ending -->
<?php endif; ?><!-- while loop-->
<?php endwhile; // ending while loop ?>
<?php else: ?>
<p><?php _e( 'Sorry, no Students matched your criteria.' ); ?></p>
<?php endif; // ending condition ?>
``` |
356,990 | <p>I have created a PHP program that provides customised output based upon user input entered in HTML contact form. The HTML form & PHP output is working fine. However, when I am trying to save the data in WP database, I am not able to see any response. I have created 'wp_mealplanner' table in the database and when i am trying to manually save the data through PHPMYADMIN, it is working fine. Please let me know where am I going wrong. I am not getting any error message.</p>
<p>Please find the code below:</p>
<pre><code><?php
/* Template Name: CustomPageT1 */
$region = $_POST['Region'];
$name = $_POST['user_name'];
$email = $_POST['user_email'];
$phone = $_POST['user_phone'];
$Click_here_to_start_your_download = 'https://mydailysugar.info/wp-
content/uploads/2019/09/Blood-Glucose-Chart-A4-1.pdf';
switch ($region )
{
case 'North':
echo "<a href='$Click_here_to_start_your_download'>Click here to start your
download</a>";
die;
case 'South':
echo "<a href='$Click_here_to_start_your_download'>Click here to start your
download</a>";
die;
case 'East':
echo "<a href='$Click_here_to_start_your_download'>Click here to start your
download</a>";
die;
case 'West':
echo "<a href='$Click_here_to_start_your_download'>Click here to start your
download</a>";
die;
}
?>
<?php
if ( isset( $_POST['SUBMIT'] ) )
{
global $wpdb;
$table ='wp_mealplanner';
$data = array('name' => $_POST['user_name'],'email' =>
$_POST['user_email'],'phone' =>
$_POST['user_phone']);
$format = array('%s','%s','%d');
$wpdb->insert( $table, $data, $format );
}
?>
<html>
<head>
<title> Meal Planner </title>
</head>
<body>
<form method='POST'>
<p>Name</p> <input type='text' name='user_name'>
<p>Email</p> <input type='text' name='user_email'>
<p>Phone</p> <input type='text' name='user_phone'>
<p>Dropdown Box</p>
<select name='Region' size='1'>
<option value='North'>North
<option value='South'>South
<option value='East'>East
<option value='West'>West
</select>
<br />
<input type='submit' name ='submit' value='SUBMIT'><input
type='reset'
value='CLEAR'>
</form>
</body>
</html>
</code></pre>
| [
{
"answer_id": 356993,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You're checking <code>isset( $_POST['SUBMIT'] )</code>, but there's no field with that name. If you mean to be checking the submit button, you need to give it a <code>name</code> attribute with the right value:</p>\n\n<pre><code><input type='submit' name='SUBMIT' value='SUBMIT'>\n</code></pre>\n\n<p>Now <code>isset( $_POST['SUBMIT']</code> will be <code>true</code>, and your code will run.</p>\n\n<p>Also, you don't seem to be using <code>$wpdb->prefix</code> correctly. <code>$wpdb->prefix</code> is based on the value entered by the user during installtion, and is used to prefix the database tables automatically created by WordPress, and can be used by plugins to name their tables as well. This prefix is usually <code>wp_</code>, so if your table is named <code>wp_mealplanner</code>, then the table name should be set like this:</p>\n\n<pre><code>$table = $wpdb->prefix . 'mealplanner';\n</code></pre>\n\n<p><em>However</em>, if you manually created your table in PHPMyAdmin, then your table's name isn't <em>actually</em> based off <code>$wpdb->prefix</code>, so you should just hard-code the name you gave it:</p>\n\n<pre><code>$table = 'wp_mealplanner';\n</code></pre>\n\n<p>You would only use <code>$wpdb->prefix</code> to ensure you were querying a table that had been created using <code>$wpdb->prefix</code> in the first place, such as during plugin activation.</p>\n"
},
{
"answer_id": 357814,
"author": "Bot123",
"author_id": 181295,
"author_profile": "https://wordpress.stackexchange.com/users/181295",
"pm_score": 0,
"selected": false,
"text": "<p>Was able to resolve this.\nI had put the 'DIE' command before calling the database function.\nI shifted the 'DIE' command after the database command and was able to resolve the issue.</p>\n"
}
] | 2020/01/23 | [
"https://wordpress.stackexchange.com/questions/356990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181295/"
] | I have created a PHP program that provides customised output based upon user input entered in HTML contact form. The HTML form & PHP output is working fine. However, when I am trying to save the data in WP database, I am not able to see any response. I have created 'wp\_mealplanner' table in the database and when i am trying to manually save the data through PHPMYADMIN, it is working fine. Please let me know where am I going wrong. I am not getting any error message.
Please find the code below:
```
<?php
/* Template Name: CustomPageT1 */
$region = $_POST['Region'];
$name = $_POST['user_name'];
$email = $_POST['user_email'];
$phone = $_POST['user_phone'];
$Click_here_to_start_your_download = 'https://mydailysugar.info/wp-
content/uploads/2019/09/Blood-Glucose-Chart-A4-1.pdf';
switch ($region )
{
case 'North':
echo "<a href='$Click_here_to_start_your_download'>Click here to start your
download</a>";
die;
case 'South':
echo "<a href='$Click_here_to_start_your_download'>Click here to start your
download</a>";
die;
case 'East':
echo "<a href='$Click_here_to_start_your_download'>Click here to start your
download</a>";
die;
case 'West':
echo "<a href='$Click_here_to_start_your_download'>Click here to start your
download</a>";
die;
}
?>
<?php
if ( isset( $_POST['SUBMIT'] ) )
{
global $wpdb;
$table ='wp_mealplanner';
$data = array('name' => $_POST['user_name'],'email' =>
$_POST['user_email'],'phone' =>
$_POST['user_phone']);
$format = array('%s','%s','%d');
$wpdb->insert( $table, $data, $format );
}
?>
<html>
<head>
<title> Meal Planner </title>
</head>
<body>
<form method='POST'>
<p>Name</p> <input type='text' name='user_name'>
<p>Email</p> <input type='text' name='user_email'>
<p>Phone</p> <input type='text' name='user_phone'>
<p>Dropdown Box</p>
<select name='Region' size='1'>
<option value='North'>North
<option value='South'>South
<option value='East'>East
<option value='West'>West
</select>
<br />
<input type='submit' name ='submit' value='SUBMIT'><input
type='reset'
value='CLEAR'>
</form>
</body>
</html>
``` | You're checking `isset( $_POST['SUBMIT'] )`, but there's no field with that name. If you mean to be checking the submit button, you need to give it a `name` attribute with the right value:
```
<input type='submit' name='SUBMIT' value='SUBMIT'>
```
Now `isset( $_POST['SUBMIT']` will be `true`, and your code will run.
Also, you don't seem to be using `$wpdb->prefix` correctly. `$wpdb->prefix` is based on the value entered by the user during installtion, and is used to prefix the database tables automatically created by WordPress, and can be used by plugins to name their tables as well. This prefix is usually `wp_`, so if your table is named `wp_mealplanner`, then the table name should be set like this:
```
$table = $wpdb->prefix . 'mealplanner';
```
*However*, if you manually created your table in PHPMyAdmin, then your table's name isn't *actually* based off `$wpdb->prefix`, so you should just hard-code the name you gave it:
```
$table = 'wp_mealplanner';
```
You would only use `$wpdb->prefix` to ensure you were querying a table that had been created using `$wpdb->prefix` in the first place, such as during plugin activation. |
357,016 | <p>I'm using the Twenty Twenty theme to create a website, and I want to totally disable the automatic colors that Wordpress generates based on the accent hue. I have very specific branding guidelines to follow, and I can't have automatically generated colors appear out of nowehere. Manually overriding this stuff with CSS !important everywhere it appears is just ugly, so I was wondering if it's possible to do it in a more elegant way. And also, where can I enter specific RGB values for the accent color, instead of relying on the hue slider?</p>
| [
{
"answer_id": 357047,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 0,
"selected": false,
"text": "<p>I had never used this theme until I read your question, so I decided to install it to see what you're talking about.</p>\n\n<p>I'm with you, not a fan of the auto colors, what a horrible idea. They say its for usability. You can <a href=\"https://github.com/WordPress/twentytwenty/issues/284\" rel=\"nofollow noreferrer\">read about it HERE</a>. </p>\n\n<p>To answer your question, there is no built in way to change the colors, besides what you have already been doing. There also isn't a way to enter a specific color value for the primary color slider. </p>\n\n<p>You could however create a child theme and add your own <a href=\"https://codex.wordpress.org/Theme_Customization_API\" rel=\"nofollow noreferrer\">customizer options</a>. This would be more work then just manually overriding them in CSS like your doing.</p>\n"
},
{
"answer_id": 357117,
"author": "Aristeides",
"author_id": 17078,
"author_profile": "https://wordpress.stackexchange.com/users/17078",
"pm_score": 0,
"selected": false,
"text": "<p>It's actually pretty easy... You can use a filter on <code>theme_mod_accent_accessible_colors</code>. You can see how the option is formatted here: \n<a href=\"https://github.com/WordPress/twentytwenty/blob/master/functions.php#L636\" rel=\"nofollow noreferrer\">https://github.com/WordPress/twentytwenty/blob/master/functions.php#L636</a></p>\n"
},
{
"answer_id": 360561,
"author": "Mwesigwa",
"author_id": 184196,
"author_profile": "https://wordpress.stackexchange.com/users/184196",
"pm_score": 0,
"selected": false,
"text": "<p>You may lookup the filter-call <code>return apply_filters( 'twentytwenty_get_elements_array', $elements );</code> in functions.php then comment it out.</p>\n"
},
{
"answer_id": 361534,
"author": "Hannah Smith",
"author_id": 80587,
"author_profile": "https://wordpress.stackexchange.com/users/80587",
"pm_score": 2,
"selected": false,
"text": "<p>Building on the answer from Aristeides, here is a complete working code example of using the <code>theme_mod_acccent_accessible_colours</code> filter. This is tested and working in version 1.1 of TwentyTwenty and version 5.3.2 of WordPress.</p>\n\n<p>You can place this code in your <code>functions.php</code> file and change the colours in the array to what you'd like. In the code shown below I have changed the 'accent' colour to a dark purple (#7f5871).</p>\n\n<pre><code>/* Hook into the colours added via the customiser. */\nadd_filter( 'theme_mod_accent_accessible_colors', 'op_change_default_colours', 10, 1 );\n\n/**\n * Override the colours added in the customiser.\n *\n * @param array $default An array of the key colours being used in the theme.\n */\nfunction op_change_default_colours( $default ) {\n\n $default = array(\n 'content' => array(\n 'text' => '#000000',\n 'accent' => '#7f5871',\n 'secondary' => '#6d6d6d',\n 'borders' => '#dcd7ca',\n ),\n 'header-footer' => array(\n 'text' => '#000000',\n 'accent' => '#7f5871',\n 'secondary' => '#6d6d6d',\n 'borders' => '#dcd7ca',\n ),\n );\n\n return $default;\n}\n</code></pre>\n"
}
] | 2020/01/23 | [
"https://wordpress.stackexchange.com/questions/357016",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87906/"
] | I'm using the Twenty Twenty theme to create a website, and I want to totally disable the automatic colors that Wordpress generates based on the accent hue. I have very specific branding guidelines to follow, and I can't have automatically generated colors appear out of nowehere. Manually overriding this stuff with CSS !important everywhere it appears is just ugly, so I was wondering if it's possible to do it in a more elegant way. And also, where can I enter specific RGB values for the accent color, instead of relying on the hue slider? | Building on the answer from Aristeides, here is a complete working code example of using the `theme_mod_acccent_accessible_colours` filter. This is tested and working in version 1.1 of TwentyTwenty and version 5.3.2 of WordPress.
You can place this code in your `functions.php` file and change the colours in the array to what you'd like. In the code shown below I have changed the 'accent' colour to a dark purple (#7f5871).
```
/* Hook into the colours added via the customiser. */
add_filter( 'theme_mod_accent_accessible_colors', 'op_change_default_colours', 10, 1 );
/**
* Override the colours added in the customiser.
*
* @param array $default An array of the key colours being used in the theme.
*/
function op_change_default_colours( $default ) {
$default = array(
'content' => array(
'text' => '#000000',
'accent' => '#7f5871',
'secondary' => '#6d6d6d',
'borders' => '#dcd7ca',
),
'header-footer' => array(
'text' => '#000000',
'accent' => '#7f5871',
'secondary' => '#6d6d6d',
'borders' => '#dcd7ca',
),
);
return $default;
}
``` |
357,032 | <p>I am calling a CSS script into a specific page in my theme like this:</p>
<pre><code>function testimonial_style() {
if ( is_page( 4087 ) ) {
wp_enqueue_style( 'testimonial-css', get_template_directory_uri().'/css/testimonial.css' );
}
}
add_action('wp_enqueue_scripts', 'testimonial_style');
</code></pre>
<p>And, this code finds the parent theme:</p>
<pre><code>get_template_directory_uri().
</code></pre>
<p>What I would like to know and do is how do I pull the CSS from my child theme which is the active theme? I would rather place the CSS in there (so it is not overwritten when I update the parent theme)</p>
<p>I hope that makes sense...</p>
<p>My child theme is in the usual place, i.e. </p>
<pre><code>/wp-content/themes
</code></pre>
<p>Thanks!</p>
<p>Ah! I think I answered it > you use this:</p>
<pre><code>get_stylesheet_directory_uri()
</code></pre>
| [
{
"answer_id": 357029,
"author": "FooBar",
"author_id": 50042,
"author_profile": "https://wordpress.stackexchange.com/users/50042",
"pm_score": 0,
"selected": false,
"text": "<p>Found: <a href=\"https://gist.github.com/squarestar/37fe1ff964adaddc0697dd03155cf0d0\" rel=\"nofollow noreferrer\">https://gist.github.com/squarestar/37fe1ff964adaddc0697dd03155cf0d0</a> as well as <a href=\"https://stackoverflow.com/questions/10353859/is-it-possible-to-programmatically-install-plugins-from-wordpress-theme\">https://stackoverflow.com/questions/10353859/is-it-possible-to-programmatically-install-plugins-from-wordpress-theme</a></p>\n\n<p>Turns out there are quite a number of ways to do it, just not mentioned here at the wordpress stack exchange.</p>\n"
},
{
"answer_id": 357030,
"author": "Rahat Hameed",
"author_id": 181506,
"author_profile": "https://wordpress.stackexchange.com/users/181506",
"pm_score": 1,
"selected": false,
"text": "<p>WP CLI is best tool out there to manage plugins/ themes through command line, instead of uploading plugins through FTP or admin panel.</p>\n\n<p>Once you Install WP-CLI on your machine then run below command and see magic.</p>\n\n<blockquote>\n <p>wp plugin install bbpress --activate</p>\n</blockquote>\n\n<p>Please check WP-CLI <a href=\"https://make.wordpress.org/cli/handbook/installing/\" rel=\"nofollow noreferrer\">official documentation</a> for further understanding.</p>\n"
},
{
"answer_id": 357040,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 0,
"selected": false,
"text": "<p>PHP has a de-facto standard package manager called <em>Composer</em>. This does <strong>not only</strong> download packages (themes, plugins, the core) for you, but also solves dependency conflicts in case two of your dependencies/ packages request the same sub-package (de-duplication) and maybe even in different versions.</p>\n\n<p>There's the WordPress specific extension called <strong><a href=\"https://wecodemore.github.io/wpstarter/\" rel=\"nofollow noreferrer\">WP Starter</a></strong> that does all the heavy lifting for you in this case. I'd recommend to go with that.</p>\n\n<p>If that is too much for you, you can build a <em>monorepo</em> and use version control systems like SVN, Git, mercurial and others to download content and later on even update those packages. Be aware that while VCS are capable of managing packages, they are not meant to do so (even with their extensions). Better use the right tool for the job and use a dedicated package manager or above mentioned abstraction/ simplification/ empowerification that is specific to Wordpress.</p>\n"
}
] | 2020/01/23 | [
"https://wordpress.stackexchange.com/questions/357032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] | I am calling a CSS script into a specific page in my theme like this:
```
function testimonial_style() {
if ( is_page( 4087 ) ) {
wp_enqueue_style( 'testimonial-css', get_template_directory_uri().'/css/testimonial.css' );
}
}
add_action('wp_enqueue_scripts', 'testimonial_style');
```
And, this code finds the parent theme:
```
get_template_directory_uri().
```
What I would like to know and do is how do I pull the CSS from my child theme which is the active theme? I would rather place the CSS in there (so it is not overwritten when I update the parent theme)
I hope that makes sense...
My child theme is in the usual place, i.e.
```
/wp-content/themes
```
Thanks!
Ah! I think I answered it > you use this:
```
get_stylesheet_directory_uri()
``` | WP CLI is best tool out there to manage plugins/ themes through command line, instead of uploading plugins through FTP or admin panel.
Once you Install WP-CLI on your machine then run below command and see magic.
>
> wp plugin install bbpress --activate
>
>
>
Please check WP-CLI [official documentation](https://make.wordpress.org/cli/handbook/installing/) for further understanding. |
357,033 | <p>My gut tells me wrapping esc_attr() in intval() is redundant when it comes to escaping input, but I would like to double-check.</p>
<p>Also: considering that <code><option value="">- select no. -</option></code> is hardcoded/value is null, that chunk of input wouldn't need to be escaped, correct?</p>
<p>Here is my current code set-up:</p>
<pre><code> <select name="_number">
<option value="">- select no. -</option>
<?php
$savedNo = intval( get_post_meta( $post->ID, '_number', true ) );
for ($x = 1; $x <= 100; $x++) {
echo '<option value="'
. intval(esc_attr($x)) . '"'
. ($x === $savedNo ? ' selected="selected"' : '' )
. '>'
. 'No. ' . intval(esc_attr($x))
. '</option>';
}
?>
</select>
</code></pre>
<p>Thank you!</p>
| [
{
"answer_id": 357036,
"author": "Hector",
"author_id": 48376,
"author_profile": "https://wordpress.stackexchange.com/users/48376",
"pm_score": 3,
"selected": true,
"text": "<p>Based on <a href=\"https://developer.wordpress.org/reference/functions/esc_attr/#return\" rel=\"nofollow noreferrer\">WordPress documentation for <code>esc_attr</code> function</a>, it is returning a string value. So, If you need to have the integer value, you need using <code>intval</code> function. <strong>But</strong>, when you want to display that value or put it as part of markup, it doesn't make sense.</p>\n\n<p>Escape functions are useful for outputting and printing values. If you want to save a value in the database, the data type is a matter and you may need to use <code>intval</code> function alongside <a href=\"https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/\" rel=\"nofollow noreferrer\">sanitization</a>.</p>\n"
},
{
"answer_id": 357037,
"author": "Vitauts Stočka",
"author_id": 181289,
"author_profile": "https://wordpress.stackexchange.com/users/181289",
"pm_score": -1,
"selected": false,
"text": "<p>In your case you don't need any of these functions on <code>$x</code>, because its values are created by <code>for</code> loop and are safe.</p>\n"
}
] | 2020/01/23 | [
"https://wordpress.stackexchange.com/questions/357033",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172153/"
] | My gut tells me wrapping esc\_attr() in intval() is redundant when it comes to escaping input, but I would like to double-check.
Also: considering that `<option value="">- select no. -</option>` is hardcoded/value is null, that chunk of input wouldn't need to be escaped, correct?
Here is my current code set-up:
```
<select name="_number">
<option value="">- select no. -</option>
<?php
$savedNo = intval( get_post_meta( $post->ID, '_number', true ) );
for ($x = 1; $x <= 100; $x++) {
echo '<option value="'
. intval(esc_attr($x)) . '"'
. ($x === $savedNo ? ' selected="selected"' : '' )
. '>'
. 'No. ' . intval(esc_attr($x))
. '</option>';
}
?>
</select>
```
Thank you! | Based on [WordPress documentation for `esc_attr` function](https://developer.wordpress.org/reference/functions/esc_attr/#return), it is returning a string value. So, If you need to have the integer value, you need using `intval` function. **But**, when you want to display that value or put it as part of markup, it doesn't make sense.
Escape functions are useful for outputting and printing values. If you want to save a value in the database, the data type is a matter and you may need to use `intval` function alongside [sanitization](https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/). |
357,058 | <p>How do you hide the "Delete Note" link in the Order Notes panel? Is there a hook that can be used? </p>
<p><a href="https://i.stack.imgur.com/NbGgF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NbGgF.png" alt="Sample order note"></a></p>
| [
{
"answer_id": 357059,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": true,
"text": "<p>You can try adding this in your functions.php file:</p>\n\n<pre><code>add_action('admin_head', 'hide_delete_note_from_edit_order');\nfunction hide_delete_note_from_edit_order()\n{\n $screen = get_current_screen();\n if ($screen->post_type === \"shop_order\" && $screen->base === \"post\") {\n echo '<style>a.delete_note { display:none; }</style>';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 357306,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": 1,
"selected": false,
"text": "<p>The answer given by <a href=\"https://wordpress.stackexchange.com/users/135085/dharmishtha-patel\">Dharmishtha Patel</a> is a good method to use. \nAnother method requiring less processing is the \"Additional CSS\" functionality. </p>\n\n<p>Within your Dashboard select \"<em>Appearance | Customize | Additional CSS</em>\" to display an edit box.</p>\n\n<p>If the style you want to change is a.delete_note type the following;</p>\n\n<pre><code>.a.delete_note { display: none; }\n</code></pre>\n\n<p>or perhaps</p>\n\n<pre><code>a.delete_note { display: none }\n</code></pre>\n\n<p>This method can be used for hiding many elements and overrides existing css styles.</p>\n\n<p><a href=\"https://en.support.wordpress.com/custom-design/editing-css/\" rel=\"nofollow noreferrer\">More information can be found here.</a></p>\n"
}
] | 2020/01/24 | [
"https://wordpress.stackexchange.com/questions/357058",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181529/"
] | How do you hide the "Delete Note" link in the Order Notes panel? Is there a hook that can be used?
[](https://i.stack.imgur.com/NbGgF.png) | You can try adding this in your functions.php file:
```
add_action('admin_head', 'hide_delete_note_from_edit_order');
function hide_delete_note_from_edit_order()
{
$screen = get_current_screen();
if ($screen->post_type === "shop_order" && $screen->base === "post") {
echo '<style>a.delete_note { display:none; }</style>';
}
}
``` |
357,070 | <p>I use TwentyTwent theme and want to change its background colour by page IDs.</p>
<p>I'm not sure but when I check the functions.php, I see below lines which are related to background colours:</p>
<pre class="lang-php prettyprint-override"><code> // Custom background color.
add_theme_support(
'custom-background',
array(
'default-color' => 'f5efe0',
)
);
// Add the background option.
$background_color = get_theme_mod( 'background_color' );
if ( ! $background_color ) {
$background_color_arr = get_theme_support( 'custom-background' );
$background_color = $background_color_arr[0]['default-color'];
}
$editor_color_palette[] = array(
'name' => __( 'Background Color', 'twentytwenty' ),
'slug' => 'background',
'color' => '#' . $background_color,
);
</code></pre>
<p>Is there any simple way to change the background colour according to Page's ID?</p>
<p>Regards.</p>
| [
{
"answer_id": 357059,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": true,
"text": "<p>You can try adding this in your functions.php file:</p>\n\n<pre><code>add_action('admin_head', 'hide_delete_note_from_edit_order');\nfunction hide_delete_note_from_edit_order()\n{\n $screen = get_current_screen();\n if ($screen->post_type === \"shop_order\" && $screen->base === \"post\") {\n echo '<style>a.delete_note { display:none; }</style>';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 357306,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": 1,
"selected": false,
"text": "<p>The answer given by <a href=\"https://wordpress.stackexchange.com/users/135085/dharmishtha-patel\">Dharmishtha Patel</a> is a good method to use. \nAnother method requiring less processing is the \"Additional CSS\" functionality. </p>\n\n<p>Within your Dashboard select \"<em>Appearance | Customize | Additional CSS</em>\" to display an edit box.</p>\n\n<p>If the style you want to change is a.delete_note type the following;</p>\n\n<pre><code>.a.delete_note { display: none; }\n</code></pre>\n\n<p>or perhaps</p>\n\n<pre><code>a.delete_note { display: none }\n</code></pre>\n\n<p>This method can be used for hiding many elements and overrides existing css styles.</p>\n\n<p><a href=\"https://en.support.wordpress.com/custom-design/editing-css/\" rel=\"nofollow noreferrer\">More information can be found here.</a></p>\n"
}
] | 2020/01/24 | [
"https://wordpress.stackexchange.com/questions/357070",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153522/"
] | I use TwentyTwent theme and want to change its background colour by page IDs.
I'm not sure but when I check the functions.php, I see below lines which are related to background colours:
```php
// Custom background color.
add_theme_support(
'custom-background',
array(
'default-color' => 'f5efe0',
)
);
// Add the background option.
$background_color = get_theme_mod( 'background_color' );
if ( ! $background_color ) {
$background_color_arr = get_theme_support( 'custom-background' );
$background_color = $background_color_arr[0]['default-color'];
}
$editor_color_palette[] = array(
'name' => __( 'Background Color', 'twentytwenty' ),
'slug' => 'background',
'color' => '#' . $background_color,
);
```
Is there any simple way to change the background colour according to Page's ID?
Regards. | You can try adding this in your functions.php file:
```
add_action('admin_head', 'hide_delete_note_from_edit_order');
function hide_delete_note_from_edit_order()
{
$screen = get_current_screen();
if ($screen->post_type === "shop_order" && $screen->base === "post") {
echo '<style>a.delete_note { display:none; }</style>';
}
}
``` |
357,142 | <p>I'm in the process of changing my web host. I'm wondering about the cleanest way to migrate my WordPress blog. I'm far from being a WordPress expert, I only use it to publish a few posts. Could you say me if my way to process is correct ?</p>
<ol>
<li>I downloaded all my website and blog content on my hard drive</li>
<li>I exported a .sql of WordPress database restoration script from
PHPMyAdmin</li>
<li>I uploaded all my website and blog content on the new web host</li>
<li>I executed the .sql script to create the same database</li>
<li>I updated the wp-config.php WordPress file to update this section:</li>
</ol>
<pre><code><?php
/**
* @package WordPress
*/
define('DB_NAME', 'THE_NAME_OF_DATABASE');
define('DB_USER', 'THE_DB_USER');
define('DB_PASSWORD', 'THE_DB_PASSWORD');
define('DB_HOST', 'THE_SQL_ADRESSE');
</code></pre>
<p>Currently , my WordPress seems running perfectly. Modules are correcly installed. The only parameter I can't say if it will work correctly is the wp-admin.php access. Indeed, as I transfere also my domain on the new web host, I am on a temporary cluster domain name so when I connect me to the administration panel, I am redirected to the real domain (old webhost). I will be fixed in several days.</p>
| [
{
"answer_id": 357174,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": 1,
"selected": false,
"text": "<p>It would seem you have covered all your bases and your site is working as it should.</p>\n\n<p>An additional step I have found useful is to verify hard coded paths within your exported SQL file because problems might not appear for weeks after the move.</p>\n\n<p>I have moved a sites a few times and it seemed to be working fine, but after a few weeks I noticed some images were not appearing. My site had previously been http and I had moved to https for additional security. Some of the plugins used would save an image location into the database as <em><a href=\"http://example.com/wp-content/blahblah\" rel=\"nofollow noreferrer\">http://example.com/wp-content/blahblah</a></em> and that was incorrect.</p>\n\n<p>If I ever move my site I always search the exported text, using a text editor, for <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> and replace with <a href=\"https://example.com\" rel=\"nofollow noreferrer\">https://example.com</a>. I also check if file paths have changed such as /doc/mydomain/public_html might because /var/sites/mydomain/public_html.</p>\n\n<p>Having your site in text format gives you an opportunity to globally replace various things :)</p>\n\n<p>That fixes any items hard coded by badly written plugins. It also takes care of the Wordpress Home & URL items as mentioned by D.Dimitrov in the comments.</p>\n\n<p>I hope this helps you and others who might stumble across this.</p>\n"
},
{
"answer_id": 357301,
"author": "Anonymous",
"author_id": 181608,
"author_profile": "https://wordpress.stackexchange.com/users/181608",
"pm_score": 1,
"selected": true,
"text": "<p>My domain is now pointing the new web server host. All seems works perfectly. I can execute WordPress plugin update, my image appears... I precise that I don't change the domain name and my site was already in HTTPS.\nSo to resume, this is the steps to migrate a WordPress :</p>\n\n<ol>\n<li>Download all my website and blog content on my hard drive</li>\n<li>Export a .sql of WordPress database restoration script from\nPHPMyAdmin</li>\n<li>Upload all my website and blog content on the new web host</li>\n<li>Execute the .sql script to create the same database</li>\n<li>Update the <code>wp-config.php</code> WordPress file to update the section <code>DB_NAME, DB_USER, DB_PASSWORD, DB_HOST</code></li>\n</ol>\n"
}
] | 2020/01/25 | [
"https://wordpress.stackexchange.com/questions/357142",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181608/"
] | I'm in the process of changing my web host. I'm wondering about the cleanest way to migrate my WordPress blog. I'm far from being a WordPress expert, I only use it to publish a few posts. Could you say me if my way to process is correct ?
1. I downloaded all my website and blog content on my hard drive
2. I exported a .sql of WordPress database restoration script from
PHPMyAdmin
3. I uploaded all my website and blog content on the new web host
4. I executed the .sql script to create the same database
5. I updated the wp-config.php WordPress file to update this section:
```
<?php
/**
* @package WordPress
*/
define('DB_NAME', 'THE_NAME_OF_DATABASE');
define('DB_USER', 'THE_DB_USER');
define('DB_PASSWORD', 'THE_DB_PASSWORD');
define('DB_HOST', 'THE_SQL_ADRESSE');
```
Currently , my WordPress seems running perfectly. Modules are correcly installed. The only parameter I can't say if it will work correctly is the wp-admin.php access. Indeed, as I transfere also my domain on the new web host, I am on a temporary cluster domain name so when I connect me to the administration panel, I am redirected to the real domain (old webhost). I will be fixed in several days. | My domain is now pointing the new web server host. All seems works perfectly. I can execute WordPress plugin update, my image appears... I precise that I don't change the domain name and my site was already in HTTPS.
So to resume, this is the steps to migrate a WordPress :
1. Download all my website and blog content on my hard drive
2. Export a .sql of WordPress database restoration script from
PHPMyAdmin
3. Upload all my website and blog content on the new web host
4. Execute the .sql script to create the same database
5. Update the `wp-config.php` WordPress file to update the section `DB_NAME, DB_USER, DB_PASSWORD, DB_HOST` |
357,153 | <p>Here is my query loop:</p>
<pre><code><?php
$query = new \WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
</code></pre>
<p>I want to call $post for this:</p>
<pre><code><div>
<?php echo do_shortcode( '[svg-flag flag="' . get_post_meta( $post->ID, 'ozellikler_text', true ) . '"]' ); ?>
</div>
</code></pre>
<p>I tried to call it with this:</p>
<pre><code><?php
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
?>
</code></pre>
<p>the code doesn't call it. It gives the error:</p>
<blockquote>
<p>Fatal error: Cannot redeclare get_the_ID() (previously declared in</p>
</blockquote>
| [
{
"answer_id": 357155,
"author": "Tim Elsass",
"author_id": 80375,
"author_profile": "https://wordpress.stackexchange.com/users/80375",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\">get_the_ID</a> is a WordPress core fuction in the global namespace, so you can't make a second function called <code>get_the_ID</code> as it won't know which one to use. You should just call get_the_ID() without writing a new function.</p>\n\n<p>For your example code, you could do something like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><div>\n <?php echo do_shortcode( '[svg-flag flag=\"' . get_post_meta( get_the_ID(), 'ozellikler_text', true ) . '\"]' ); ?>\n</div>\n</code></pre>\n"
},
{
"answer_id": 357156,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>First, you don't have such thing as <code>$post->ID</code>, you have <code>$query->$post->ID</code> in your WP_Query result:</p>\n\n<pre><code><?php\n$my_post_meta = get_post_meta(\n $query->$post->ID, // note this\n 'ozellikler_text',\n true\n);\n\necho do_shortcode( '[svg-flag flag=\"' . $my_post_meta . '\"]' );\n</code></pre>\n\n<p>Second, as already written in the error text, you can't redeclare already declared built-in function. Simply use it:</p>\n\n<pre><code><?php\n$my_post_meta = get_post_meta(\n get_the_ID(), // use the built-in function\n 'ozellikler_text',\n true\n);\n\necho do_shortcode( '[svg-flag flag=\"' . $my_post_meta . '\"]' );\n</code></pre>\n"
}
] | 2020/01/25 | [
"https://wordpress.stackexchange.com/questions/357153",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180385/"
] | Here is my query loop:
```
<?php
$query = new \WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
```
I want to call $post for this:
```
<div>
<?php echo do_shortcode( '[svg-flag flag="' . get_post_meta( $post->ID, 'ozellikler_text', true ) . '"]' ); ?>
</div>
```
I tried to call it with this:
```
<?php
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
?>
```
the code doesn't call it. It gives the error:
>
> Fatal error: Cannot redeclare get\_the\_ID() (previously declared in
>
>
> | [get\_the\_ID](https://developer.wordpress.org/reference/functions/get_the_id/) is a WordPress core fuction in the global namespace, so you can't make a second function called `get_the_ID` as it won't know which one to use. You should just call get\_the\_ID() without writing a new function.
For your example code, you could do something like this:
```php
<div>
<?php echo do_shortcode( '[svg-flag flag="' . get_post_meta( get_the_ID(), 'ozellikler_text', true ) . '"]' ); ?>
</div>
``` |
357,172 | <p>For development I want to be able to use my wordpress site with localhost, and with a variety of IPs, maybe even with some throwaways domain names.</p>
<p>Now wordpress doesn't allow, you have to choose 1 "site url" and change it every time you decide to use a different port or different test server IP.</p>
<p>I am aware I can change hosts file on my local computer, but that doesn't work if I am hosting a site temporarily for a client to test. I don't want to have to get them to change their hosts file.</p>
<p>How can I modify wordpress to make this work? Is there a plugin that does such a thing? If not, how can I make my own plugin or hack wordpress to make it do what I want? I am a developer but I don't know wordpress, php and apache very well.</p>
<p>Could it be as simple as making a plugin that overrides global vars like <code>site_url</code> and what not?</p>
<p>Example the wp site should load and not redirect if I visit:</p>
<p><code>http://localhost</code> (assuming I'm listening on port 80)</p>
<p><code>http://localhost:3000</code> (assuming I'm listening on port 3000)</p>
<p><code>http://wordpress-test</code> (assuming I change my hosts file)</p>
<p><code>http://123.123.123.123</code> (assuming the site is listening on that server at port 80)</p>
| [
{
"answer_id": 357175,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": -1,
"selected": false,
"text": "<p>Wordpress is PHP based and requires a database server such as MySQL or MariaDB.</p>\n\n<p>I would suggest using a development environment such as LAMP, WAMP or similar. The software is free and will install a development environment including Apache, PHP, MySQL and sometimes Phpmyadmin.</p>\n\n<p>You will get Apache, PHP, MySQL and a control panel for setting up test domains stored locally on your PC.</p>\n\n<p>You wont really need to be an expert in any of the packages installed as you will have a control panel for setting up databases (needed by Wordpress) and for creating test domains.</p>\n\n<p>I am assuming you are using a Windows operating system, in which case you want it's an easy process. The <a href=\"https://ampps.com/\" rel=\"nofollow noreferrer\">AMP</a> style packages are available for both Windows and Linux.</p>\n\n<p>Setting up a good test environment will give you good experience and it is an excellent way to learn because you can't hurt anyone but yourself if you make a mistake.</p>\n\n<p>There are thousands of pages on the net with help using all the packages included in the AMP distributions.</p>\n\n<p>I hope this helps you.</p>\n"
},
{
"answer_id": 357178,
"author": "Tim Elsass",
"author_id": 80375,
"author_profile": "https://wordpress.stackexchange.com/users/80375",
"pm_score": 0,
"selected": false,
"text": "<p>There's a bit more than just the option to update unfortunately. I'd recommend reading over <a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/</a> to learn about what is involved first. As far as plugin solutions, there's lots that exist already, which would be a safer route than rolling your own. <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better Search and Replace</a> is a popular one.</p>\n\n<p>Since you're going to be doing this url change for client previews vs local dev vs production - I'd assume you either already have wp-cli or can easily get it up and running. It already has a built in search and replace you can do:</p>\n\n<pre><code>wp search-replace http://local.test https://throwaway-domain.com/subdirectory --skip-columns=guid --dry-run\n</code></pre>\n\n<p>From <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">wp-cli documentation for search-replace</a>, this script is useful as well:</p>\n\n<pre><code># Bash script: Search/replace production to development url (multisite compatible)\n#!/bin/bash\nif $(wp --url=http://example.com core is-installed --network); then\n wp search-replace --url=http://example.com 'http://example.com' 'http://example.test' --recurse-objects --network --skip-columns=guid --skip-tables=wp_users\nelse\n wp search-replace 'http://example.com' 'http://example.test' --recurse-objects --skip-columns=guid --skip-tables=wp_users\nfi\n</code></pre>\n\n<p><strong>Note</strong>: <em>You might have noticed the flag <code>--skip-columns=guid</code> in both examples, which is explained in the first link under <a href=\"https://wordpress.org/support/article/changing-the-site-url/#important-guid-note\" rel=\"nofollow noreferrer\">Important GUID Note</a>. Similarly the <strong>Better Search and Replace</strong> plugin mentioned has a checkbox to skip Replacing GUIDs.</em></p>\n\n<p>As you mentioned you use docker in another comment, you can take a look at this <a href=\"https://stackoverflow.com/questions/50999848/how-to-run-wp-cli-in-docker-compose-yml\">StackOverflow question</a>.</p>\n"
},
{
"answer_id": 357188,
"author": "Vitauts Stočka",
"author_id": 181289,
"author_profile": "https://wordpress.stackexchange.com/users/181289",
"pm_score": 0,
"selected": false,
"text": "<p>You can try theese hook filters</p>\n\n<pre><code>add_filter('home_url', 'my_url', 10, 2);\nadd_filter('site_url', 'my_url', 10, 2);\n\nfunction my_url($url, $path) {\n return 'http://your-dev-hostname-or-ip-here/' . $path;\n}\n</code></pre>\n\n<p>However keep in mind, that original (real) site url will still be used in many places in content. To fix that you can use additional hook on <code>the_content</code> and do string replacement there.</p>\n"
}
] | 2020/01/26 | [
"https://wordpress.stackexchange.com/questions/357172",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123580/"
] | For development I want to be able to use my wordpress site with localhost, and with a variety of IPs, maybe even with some throwaways domain names.
Now wordpress doesn't allow, you have to choose 1 "site url" and change it every time you decide to use a different port or different test server IP.
I am aware I can change hosts file on my local computer, but that doesn't work if I am hosting a site temporarily for a client to test. I don't want to have to get them to change their hosts file.
How can I modify wordpress to make this work? Is there a plugin that does such a thing? If not, how can I make my own plugin or hack wordpress to make it do what I want? I am a developer but I don't know wordpress, php and apache very well.
Could it be as simple as making a plugin that overrides global vars like `site_url` and what not?
Example the wp site should load and not redirect if I visit:
`http://localhost` (assuming I'm listening on port 80)
`http://localhost:3000` (assuming I'm listening on port 3000)
`http://wordpress-test` (assuming I change my hosts file)
`http://123.123.123.123` (assuming the site is listening on that server at port 80) | There's a bit more than just the option to update unfortunately. I'd recommend reading over <https://wordpress.org/support/article/changing-the-site-url/> to learn about what is involved first. As far as plugin solutions, there's lots that exist already, which would be a safer route than rolling your own. [Better Search and Replace](https://wordpress.org/plugins/better-search-replace/) is a popular one.
Since you're going to be doing this url change for client previews vs local dev vs production - I'd assume you either already have wp-cli or can easily get it up and running. It already has a built in search and replace you can do:
```
wp search-replace http://local.test https://throwaway-domain.com/subdirectory --skip-columns=guid --dry-run
```
From [wp-cli documentation for search-replace](https://developer.wordpress.org/cli/commands/search-replace/), this script is useful as well:
```
# Bash script: Search/replace production to development url (multisite compatible)
#!/bin/bash
if $(wp --url=http://example.com core is-installed --network); then
wp search-replace --url=http://example.com 'http://example.com' 'http://example.test' --recurse-objects --network --skip-columns=guid --skip-tables=wp_users
else
wp search-replace 'http://example.com' 'http://example.test' --recurse-objects --skip-columns=guid --skip-tables=wp_users
fi
```
**Note**: *You might have noticed the flag `--skip-columns=guid` in both examples, which is explained in the first link under [Important GUID Note](https://wordpress.org/support/article/changing-the-site-url/#important-guid-note). Similarly the **Better Search and Replace** plugin mentioned has a checkbox to skip Replacing GUIDs.*
As you mentioned you use docker in another comment, you can take a look at this [StackOverflow question](https://stackoverflow.com/questions/50999848/how-to-run-wp-cli-in-docker-compose-yml). |
357,187 | <p>Hello I need a form in one wordpress page where an user can search pages by specific meta data.</p>
<p>I found how to do search:
<a href="https://rudrastyh.com/wordpress/meta_query.html#query_meta_values" rel="nofollow noreferrer">https://rudrastyh.com/wordpress/meta_query.html#query_meta_values</a></p>
<p>But how should I create form which then call the query with arguments? After that it then should display the search result.</p>
<p>Currently I have this Form on my page:</p>
<p><code><form action="../process.php" method="post" name="myForm">
<p>Name <input id="name" type="text" name="name" />
</p>
<p>eMail <input id="email" type="text" name="email" />
</p>
<input type="submit" value="Submit" />
</form></code></p>
<p>Unfortunatelly I still didn't found solution. It would be great if you could help me.</p>
<p>Thanx
Floh</p>
| [
{
"answer_id": 357175,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": -1,
"selected": false,
"text": "<p>Wordpress is PHP based and requires a database server such as MySQL or MariaDB.</p>\n\n<p>I would suggest using a development environment such as LAMP, WAMP or similar. The software is free and will install a development environment including Apache, PHP, MySQL and sometimes Phpmyadmin.</p>\n\n<p>You will get Apache, PHP, MySQL and a control panel for setting up test domains stored locally on your PC.</p>\n\n<p>You wont really need to be an expert in any of the packages installed as you will have a control panel for setting up databases (needed by Wordpress) and for creating test domains.</p>\n\n<p>I am assuming you are using a Windows operating system, in which case you want it's an easy process. The <a href=\"https://ampps.com/\" rel=\"nofollow noreferrer\">AMP</a> style packages are available for both Windows and Linux.</p>\n\n<p>Setting up a good test environment will give you good experience and it is an excellent way to learn because you can't hurt anyone but yourself if you make a mistake.</p>\n\n<p>There are thousands of pages on the net with help using all the packages included in the AMP distributions.</p>\n\n<p>I hope this helps you.</p>\n"
},
{
"answer_id": 357178,
"author": "Tim Elsass",
"author_id": 80375,
"author_profile": "https://wordpress.stackexchange.com/users/80375",
"pm_score": 0,
"selected": false,
"text": "<p>There's a bit more than just the option to update unfortunately. I'd recommend reading over <a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/</a> to learn about what is involved first. As far as plugin solutions, there's lots that exist already, which would be a safer route than rolling your own. <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better Search and Replace</a> is a popular one.</p>\n\n<p>Since you're going to be doing this url change for client previews vs local dev vs production - I'd assume you either already have wp-cli or can easily get it up and running. It already has a built in search and replace you can do:</p>\n\n<pre><code>wp search-replace http://local.test https://throwaway-domain.com/subdirectory --skip-columns=guid --dry-run\n</code></pre>\n\n<p>From <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">wp-cli documentation for search-replace</a>, this script is useful as well:</p>\n\n<pre><code># Bash script: Search/replace production to development url (multisite compatible)\n#!/bin/bash\nif $(wp --url=http://example.com core is-installed --network); then\n wp search-replace --url=http://example.com 'http://example.com' 'http://example.test' --recurse-objects --network --skip-columns=guid --skip-tables=wp_users\nelse\n wp search-replace 'http://example.com' 'http://example.test' --recurse-objects --skip-columns=guid --skip-tables=wp_users\nfi\n</code></pre>\n\n<p><strong>Note</strong>: <em>You might have noticed the flag <code>--skip-columns=guid</code> in both examples, which is explained in the first link under <a href=\"https://wordpress.org/support/article/changing-the-site-url/#important-guid-note\" rel=\"nofollow noreferrer\">Important GUID Note</a>. Similarly the <strong>Better Search and Replace</strong> plugin mentioned has a checkbox to skip Replacing GUIDs.</em></p>\n\n<p>As you mentioned you use docker in another comment, you can take a look at this <a href=\"https://stackoverflow.com/questions/50999848/how-to-run-wp-cli-in-docker-compose-yml\">StackOverflow question</a>.</p>\n"
},
{
"answer_id": 357188,
"author": "Vitauts Stočka",
"author_id": 181289,
"author_profile": "https://wordpress.stackexchange.com/users/181289",
"pm_score": 0,
"selected": false,
"text": "<p>You can try theese hook filters</p>\n\n<pre><code>add_filter('home_url', 'my_url', 10, 2);\nadd_filter('site_url', 'my_url', 10, 2);\n\nfunction my_url($url, $path) {\n return 'http://your-dev-hostname-or-ip-here/' . $path;\n}\n</code></pre>\n\n<p>However keep in mind, that original (real) site url will still be used in many places in content. To fix that you can use additional hook on <code>the_content</code> and do string replacement there.</p>\n"
}
] | 2020/01/26 | [
"https://wordpress.stackexchange.com/questions/357187",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181645/"
] | Hello I need a form in one wordpress page where an user can search pages by specific meta data.
I found how to do search:
<https://rudrastyh.com/wordpress/meta_query.html#query_meta_values>
But how should I create form which then call the query with arguments? After that it then should display the search result.
Currently I have this Form on my page:
`<form action="../process.php" method="post" name="myForm">
<p>Name <input id="name" type="text" name="name" />
</p>
<p>eMail <input id="email" type="text" name="email" />
</p>
<input type="submit" value="Submit" />
</form>`
Unfortunatelly I still didn't found solution. It would be great if you could help me.
Thanx
Floh | There's a bit more than just the option to update unfortunately. I'd recommend reading over <https://wordpress.org/support/article/changing-the-site-url/> to learn about what is involved first. As far as plugin solutions, there's lots that exist already, which would be a safer route than rolling your own. [Better Search and Replace](https://wordpress.org/plugins/better-search-replace/) is a popular one.
Since you're going to be doing this url change for client previews vs local dev vs production - I'd assume you either already have wp-cli or can easily get it up and running. It already has a built in search and replace you can do:
```
wp search-replace http://local.test https://throwaway-domain.com/subdirectory --skip-columns=guid --dry-run
```
From [wp-cli documentation for search-replace](https://developer.wordpress.org/cli/commands/search-replace/), this script is useful as well:
```
# Bash script: Search/replace production to development url (multisite compatible)
#!/bin/bash
if $(wp --url=http://example.com core is-installed --network); then
wp search-replace --url=http://example.com 'http://example.com' 'http://example.test' --recurse-objects --network --skip-columns=guid --skip-tables=wp_users
else
wp search-replace 'http://example.com' 'http://example.test' --recurse-objects --skip-columns=guid --skip-tables=wp_users
fi
```
**Note**: *You might have noticed the flag `--skip-columns=guid` in both examples, which is explained in the first link under [Important GUID Note](https://wordpress.org/support/article/changing-the-site-url/#important-guid-note). Similarly the **Better Search and Replace** plugin mentioned has a checkbox to skip Replacing GUIDs.*
As you mentioned you use docker in another comment, you can take a look at this [StackOverflow question](https://stackoverflow.com/questions/50999848/how-to-run-wp-cli-in-docker-compose-yml). |
357,209 | <p>I have two option callbacks in my plugin, one with a ckeckbox and one with a select field. The first one is working perfectly, the second not. The select field doesn't save its value. I double checked the code which registers the two settings, I assume my mistake is somewhere in the callback.</p>
<p>Any ideas?</p>
<p>Checkbox (works):</p>
<pre><code>public function myplugin_post_menu_cb() {
echo '<input type="checkbox" name="' . $this->option_name . '_post_menu' . '" value="1" "' . checked(1, get_option('myplugin_post_menu'), false) . '" />';
}
</code></pre>
<p>Select (doesn't work):</p>
<pre><code>public function myplugin_admin_bar_cb() {
echo '<select name="' . $this->option_name . '_admin_bar' . '">';
echo '<option value="1" "' . selected( get_option('myplugin_admin_bar'), 1 ) . '">1</option>';
echo '<option value="2" "' . selected( get_option('myplugin_admin_bar'), 2 ) . '">2</option>';
echo '</select>';
}
</code></pre>
<p>Thanks for the help.</p>
| [
{
"answer_id": 357175,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": -1,
"selected": false,
"text": "<p>Wordpress is PHP based and requires a database server such as MySQL or MariaDB.</p>\n\n<p>I would suggest using a development environment such as LAMP, WAMP or similar. The software is free and will install a development environment including Apache, PHP, MySQL and sometimes Phpmyadmin.</p>\n\n<p>You will get Apache, PHP, MySQL and a control panel for setting up test domains stored locally on your PC.</p>\n\n<p>You wont really need to be an expert in any of the packages installed as you will have a control panel for setting up databases (needed by Wordpress) and for creating test domains.</p>\n\n<p>I am assuming you are using a Windows operating system, in which case you want it's an easy process. The <a href=\"https://ampps.com/\" rel=\"nofollow noreferrer\">AMP</a> style packages are available for both Windows and Linux.</p>\n\n<p>Setting up a good test environment will give you good experience and it is an excellent way to learn because you can't hurt anyone but yourself if you make a mistake.</p>\n\n<p>There are thousands of pages on the net with help using all the packages included in the AMP distributions.</p>\n\n<p>I hope this helps you.</p>\n"
},
{
"answer_id": 357178,
"author": "Tim Elsass",
"author_id": 80375,
"author_profile": "https://wordpress.stackexchange.com/users/80375",
"pm_score": 0,
"selected": false,
"text": "<p>There's a bit more than just the option to update unfortunately. I'd recommend reading over <a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/</a> to learn about what is involved first. As far as plugin solutions, there's lots that exist already, which would be a safer route than rolling your own. <a href=\"https://wordpress.org/plugins/better-search-replace/\" rel=\"nofollow noreferrer\">Better Search and Replace</a> is a popular one.</p>\n\n<p>Since you're going to be doing this url change for client previews vs local dev vs production - I'd assume you either already have wp-cli or can easily get it up and running. It already has a built in search and replace you can do:</p>\n\n<pre><code>wp search-replace http://local.test https://throwaway-domain.com/subdirectory --skip-columns=guid --dry-run\n</code></pre>\n\n<p>From <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">wp-cli documentation for search-replace</a>, this script is useful as well:</p>\n\n<pre><code># Bash script: Search/replace production to development url (multisite compatible)\n#!/bin/bash\nif $(wp --url=http://example.com core is-installed --network); then\n wp search-replace --url=http://example.com 'http://example.com' 'http://example.test' --recurse-objects --network --skip-columns=guid --skip-tables=wp_users\nelse\n wp search-replace 'http://example.com' 'http://example.test' --recurse-objects --skip-columns=guid --skip-tables=wp_users\nfi\n</code></pre>\n\n<p><strong>Note</strong>: <em>You might have noticed the flag <code>--skip-columns=guid</code> in both examples, which is explained in the first link under <a href=\"https://wordpress.org/support/article/changing-the-site-url/#important-guid-note\" rel=\"nofollow noreferrer\">Important GUID Note</a>. Similarly the <strong>Better Search and Replace</strong> plugin mentioned has a checkbox to skip Replacing GUIDs.</em></p>\n\n<p>As you mentioned you use docker in another comment, you can take a look at this <a href=\"https://stackoverflow.com/questions/50999848/how-to-run-wp-cli-in-docker-compose-yml\">StackOverflow question</a>.</p>\n"
},
{
"answer_id": 357188,
"author": "Vitauts Stočka",
"author_id": 181289,
"author_profile": "https://wordpress.stackexchange.com/users/181289",
"pm_score": 0,
"selected": false,
"text": "<p>You can try theese hook filters</p>\n\n<pre><code>add_filter('home_url', 'my_url', 10, 2);\nadd_filter('site_url', 'my_url', 10, 2);\n\nfunction my_url($url, $path) {\n return 'http://your-dev-hostname-or-ip-here/' . $path;\n}\n</code></pre>\n\n<p>However keep in mind, that original (real) site url will still be used in many places in content. To fix that you can use additional hook on <code>the_content</code> and do string replacement there.</p>\n"
}
] | 2020/01/26 | [
"https://wordpress.stackexchange.com/questions/357209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59113/"
] | I have two option callbacks in my plugin, one with a ckeckbox and one with a select field. The first one is working perfectly, the second not. The select field doesn't save its value. I double checked the code which registers the two settings, I assume my mistake is somewhere in the callback.
Any ideas?
Checkbox (works):
```
public function myplugin_post_menu_cb() {
echo '<input type="checkbox" name="' . $this->option_name . '_post_menu' . '" value="1" "' . checked(1, get_option('myplugin_post_menu'), false) . '" />';
}
```
Select (doesn't work):
```
public function myplugin_admin_bar_cb() {
echo '<select name="' . $this->option_name . '_admin_bar' . '">';
echo '<option value="1" "' . selected( get_option('myplugin_admin_bar'), 1 ) . '">1</option>';
echo '<option value="2" "' . selected( get_option('myplugin_admin_bar'), 2 ) . '">2</option>';
echo '</select>';
}
```
Thanks for the help. | There's a bit more than just the option to update unfortunately. I'd recommend reading over <https://wordpress.org/support/article/changing-the-site-url/> to learn about what is involved first. As far as plugin solutions, there's lots that exist already, which would be a safer route than rolling your own. [Better Search and Replace](https://wordpress.org/plugins/better-search-replace/) is a popular one.
Since you're going to be doing this url change for client previews vs local dev vs production - I'd assume you either already have wp-cli or can easily get it up and running. It already has a built in search and replace you can do:
```
wp search-replace http://local.test https://throwaway-domain.com/subdirectory --skip-columns=guid --dry-run
```
From [wp-cli documentation for search-replace](https://developer.wordpress.org/cli/commands/search-replace/), this script is useful as well:
```
# Bash script: Search/replace production to development url (multisite compatible)
#!/bin/bash
if $(wp --url=http://example.com core is-installed --network); then
wp search-replace --url=http://example.com 'http://example.com' 'http://example.test' --recurse-objects --network --skip-columns=guid --skip-tables=wp_users
else
wp search-replace 'http://example.com' 'http://example.test' --recurse-objects --skip-columns=guid --skip-tables=wp_users
fi
```
**Note**: *You might have noticed the flag `--skip-columns=guid` in both examples, which is explained in the first link under [Important GUID Note](https://wordpress.org/support/article/changing-the-site-url/#important-guid-note). Similarly the **Better Search and Replace** plugin mentioned has a checkbox to skip Replacing GUIDs.*
As you mentioned you use docker in another comment, you can take a look at this [StackOverflow question](https://stackoverflow.com/questions/50999848/how-to-run-wp-cli-in-docker-compose-yml). |
357,212 | <p>Until two days ago the site was working fine. Yesterday, I've done nothing to it and now when I try to go to the web site it downloads a file that contains:</p>
<pre><code><?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define( 'WP_USE_THEMES', true );
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
</code></pre>
<p>I've already tried changing the name of the plugin and theme directory to see if the problem comes from there but it didn't helped, I've also tried to rename the .htaccess file but it won't regenerate and I've also verified permissions and they are fine.</p>
| [
{
"answer_id": 357224,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": true,
"text": "<p>Sounds to me like PHP is not running on your system, or (perhaps) an older version of PHP. </p>\n\n<p>But you can check PHP status by creating a simple PHP file with the command </p>\n\n<pre><code>phpinfo();\n</code></pre>\n\n<p>in it and loading that page in your browser. That should show you the current settings of PHP, if it is running. And perhaps check with your hosting support to see what they say. </p>\n\n<p>There are many googles/bings/ducks about how to ensure PHP is running on your server. I'd start there.</p>\n"
},
{
"answer_id": 357240,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": 0,
"selected": false,
"text": "<p>The decision to process or download files, as you've described, is often a function of your http server rather than wordpress.</p>\n\n<p>Has your host made any changes to your server configuration? Has PHP been recently upgraded?</p>\n\n<p>Make certain your PHP Handler is configured correctly. Also verify all files associated with Wordpress are present and haven't been removed via malicious software.</p>\n\n<p>A google search yields lots of results, nearly all being an issue with the http server.</p>\n\n<p><a href=\"https://www.google.com/search?q=apache%20downloads%20files%20rather%20than%20displaying&oq=apache%20downloads%20files%20rather%20than%20displaying&aqs=chrome..69i57.9291j0j7&client=ubuntu&sourceid=chrome&ie=UTF-8\" rel=\"nofollow noreferrer\">Google Search Results</a></p>\n\n<p>I'd have left this as a comment but I'm so new here I can't leave comments.</p>\n"
}
] | 2020/01/26 | [
"https://wordpress.stackexchange.com/questions/357212",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181662/"
] | Until two days ago the site was working fine. Yesterday, I've done nothing to it and now when I try to go to the web site it downloads a file that contains:
```
<?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define( 'WP_USE_THEMES', true );
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
```
I've already tried changing the name of the plugin and theme directory to see if the problem comes from there but it didn't helped, I've also tried to rename the .htaccess file but it won't regenerate and I've also verified permissions and they are fine. | Sounds to me like PHP is not running on your system, or (perhaps) an older version of PHP.
But you can check PHP status by creating a simple PHP file with the command
```
phpinfo();
```
in it and loading that page in your browser. That should show you the current settings of PHP, if it is running. And perhaps check with your hosting support to see what they say.
There are many googles/bings/ducks about how to ensure PHP is running on your server. I'd start there. |
357,246 | <p>I've been using do_action to generate multiple action hooks in the loop. It seems unlucky for me the do_action not working.</p>
<pre><code>function ltc_generate_input_fields($fields = array()) {
echo "Hello World";
if (empty($fields) || !is_array($fields)) return;
foreach($fields as $field) {
if (!is_array($field) || empty($field)) continue;
$name = (array_key_exists('name', $field)) ? $field['name'] : '';
$key = (!empty($name)) ? strtolower(str_replace(' ', '_', $name)) : '';
$display_name = (!empty($name)) ? ucwords($name) : '';
$type = (array_key_exists('type', $field)) ? $field['type'] : 'text';
$id = (array_key_exists('id', $field)) ? $field['id'] : '';
$id = (empty($id)) ? strtolower(str_replace(' ', '-', $name)) : $id;
$classes = (array_key_exists('classes', $field)) ? $field['classes'] : '';
?>
<div class="notebook-form-elements notebook-inputs">
<div class="notebook-inputs-wrap">
<label for="<?php echo $id; ?>"><?php echo $display_name ?></label>
<input type="<?php echo $type; ?>" id="<?php echo $id; ?>" class="notebook-features<?php echo $classes ?>" name="<?php echo $key; ?>" value="">
</div>
</div>
<?php
}
}
function ltc_generate_notebook_features_sections($sections = array()) {
if (!is_array($sections) || empty($sections)) return;
foreach($sections as $section) {
if (!is_array($section)) return;
$ltc_section_class = strtolower(str_replace(' ', '-',$section['name']));
$section_action = strtolower(str_replace(' ', '_',$section['name']));
$section_action = 'ltc_' .$section_action .'_content';
$fields = (array_key_exists('fields', $section)) ? $section['fields'] : '';
?>
<div class="notebook-section section-<?php echo $ltc_section_class ?>">
<div class="notebook-section-heading">
<h3 class="notebook-title"><?php echo $section['name']; ?></h3>
</div>
<div class="notebook-section-content">
<?php do_action('ltc_before' . $section_action .'_content'); ?>
<?php do_action($section_action); ?>
<?php do_action('ltc_after' . $section_action .'_content'); ?>
</div>
</div>
<?php
if (!is_array($fields) || empty($fields)) continue;
var_dump(has_action($section_action)); //return false
var_dump($section_action); // return 'ltc_memory_content
if (!has_action($section_action)) continue;
add_action( $section_action, 'ltc_generate_input_fields', 5, 1);
}
}
</code></pre>
<p>I used the bellow function to generate section.</p>
<pre><code>function ltc_add_notebook_sections() {
$sections = array(
array(
'name' => 'Memory',
'fields' => array(
array(
'name' => 'Ram Type',
),
array(
'name' => 'Memory Slots'
),
array(
'name' => 'Ram Speed'
),
array(
'name' => 'Expandable'
),
array(
'name' => 'Capacity'
)
)
),
array(
'name' => 'Display Detail'
);
ltc_generate_notebook_features_sections($sections);
}
add_action('ltc_notebook_features_sections', 'ltc_add_notebook_sections', 10, 1);
</code></pre>
| [
{
"answer_id": 357224,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": true,
"text": "<p>Sounds to me like PHP is not running on your system, or (perhaps) an older version of PHP. </p>\n\n<p>But you can check PHP status by creating a simple PHP file with the command </p>\n\n<pre><code>phpinfo();\n</code></pre>\n\n<p>in it and loading that page in your browser. That should show you the current settings of PHP, if it is running. And perhaps check with your hosting support to see what they say. </p>\n\n<p>There are many googles/bings/ducks about how to ensure PHP is running on your server. I'd start there.</p>\n"
},
{
"answer_id": 357240,
"author": "Admiral Noisy Bottom",
"author_id": 181142,
"author_profile": "https://wordpress.stackexchange.com/users/181142",
"pm_score": 0,
"selected": false,
"text": "<p>The decision to process or download files, as you've described, is often a function of your http server rather than wordpress.</p>\n\n<p>Has your host made any changes to your server configuration? Has PHP been recently upgraded?</p>\n\n<p>Make certain your PHP Handler is configured correctly. Also verify all files associated with Wordpress are present and haven't been removed via malicious software.</p>\n\n<p>A google search yields lots of results, nearly all being an issue with the http server.</p>\n\n<p><a href=\"https://www.google.com/search?q=apache%20downloads%20files%20rather%20than%20displaying&oq=apache%20downloads%20files%20rather%20than%20displaying&aqs=chrome..69i57.9291j0j7&client=ubuntu&sourceid=chrome&ie=UTF-8\" rel=\"nofollow noreferrer\">Google Search Results</a></p>\n\n<p>I'd have left this as a comment but I'm so new here I can't leave comments.</p>\n"
}
] | 2020/01/27 | [
"https://wordpress.stackexchange.com/questions/357246",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101518/"
] | I've been using do\_action to generate multiple action hooks in the loop. It seems unlucky for me the do\_action not working.
```
function ltc_generate_input_fields($fields = array()) {
echo "Hello World";
if (empty($fields) || !is_array($fields)) return;
foreach($fields as $field) {
if (!is_array($field) || empty($field)) continue;
$name = (array_key_exists('name', $field)) ? $field['name'] : '';
$key = (!empty($name)) ? strtolower(str_replace(' ', '_', $name)) : '';
$display_name = (!empty($name)) ? ucwords($name) : '';
$type = (array_key_exists('type', $field)) ? $field['type'] : 'text';
$id = (array_key_exists('id', $field)) ? $field['id'] : '';
$id = (empty($id)) ? strtolower(str_replace(' ', '-', $name)) : $id;
$classes = (array_key_exists('classes', $field)) ? $field['classes'] : '';
?>
<div class="notebook-form-elements notebook-inputs">
<div class="notebook-inputs-wrap">
<label for="<?php echo $id; ?>"><?php echo $display_name ?></label>
<input type="<?php echo $type; ?>" id="<?php echo $id; ?>" class="notebook-features<?php echo $classes ?>" name="<?php echo $key; ?>" value="">
</div>
</div>
<?php
}
}
function ltc_generate_notebook_features_sections($sections = array()) {
if (!is_array($sections) || empty($sections)) return;
foreach($sections as $section) {
if (!is_array($section)) return;
$ltc_section_class = strtolower(str_replace(' ', '-',$section['name']));
$section_action = strtolower(str_replace(' ', '_',$section['name']));
$section_action = 'ltc_' .$section_action .'_content';
$fields = (array_key_exists('fields', $section)) ? $section['fields'] : '';
?>
<div class="notebook-section section-<?php echo $ltc_section_class ?>">
<div class="notebook-section-heading">
<h3 class="notebook-title"><?php echo $section['name']; ?></h3>
</div>
<div class="notebook-section-content">
<?php do_action('ltc_before' . $section_action .'_content'); ?>
<?php do_action($section_action); ?>
<?php do_action('ltc_after' . $section_action .'_content'); ?>
</div>
</div>
<?php
if (!is_array($fields) || empty($fields)) continue;
var_dump(has_action($section_action)); //return false
var_dump($section_action); // return 'ltc_memory_content
if (!has_action($section_action)) continue;
add_action( $section_action, 'ltc_generate_input_fields', 5, 1);
}
}
```
I used the bellow function to generate section.
```
function ltc_add_notebook_sections() {
$sections = array(
array(
'name' => 'Memory',
'fields' => array(
array(
'name' => 'Ram Type',
),
array(
'name' => 'Memory Slots'
),
array(
'name' => 'Ram Speed'
),
array(
'name' => 'Expandable'
),
array(
'name' => 'Capacity'
)
)
),
array(
'name' => 'Display Detail'
);
ltc_generate_notebook_features_sections($sections);
}
add_action('ltc_notebook_features_sections', 'ltc_add_notebook_sections', 10, 1);
``` | Sounds to me like PHP is not running on your system, or (perhaps) an older version of PHP.
But you can check PHP status by creating a simple PHP file with the command
```
phpinfo();
```
in it and loading that page in your browser. That should show you the current settings of PHP, if it is running. And perhaps check with your hosting support to see what they say.
There are many googles/bings/ducks about how to ensure PHP is running on your server. I'd start there. |
357,309 | <p>I have a custom post type that I'm importing into the front page of the site with <code>WP_Query()</code>, but I can't seem to get the custom taxonomy to show.</p>
<p>I've placed a div in the HTML and inside this I'm calling <code>the_category()</code>, but nothing is being outputted to the front end.</p>
<p>The taxonomy is showing in the back end and I've added a custom taxonomy (category) to all of the three posts I want to show.</p>
<pre><code><?php
$homePageNews = new WP_Query(array(
'posts_per_page' => 3,
'post_type'=> 'news'
));
while($homePageNews->have_posts()){
$homePageNews->the_post(); ?>
<article class="article top-article lastest-top-article">
<?php the_post_thumbnail('post-thumbnail',
['class' => 'image latest-top-image hover-class']); ?>
<div class="cat"><?php the_category( ', ' ); ?></div>
<div class="content-wrapper content-wrapper-mobile-padding">
<h3 class="td no-bottom-margin hover-class"><a class="top-latest-heading" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<hr>
<p><?php the_content(); ?></h3></p>
</div>
</article>
<?php } ?>
<?php wp_reset_postdata(); ?>
</code></pre>
| [
{
"answer_id": 357324,
"author": "Dip Patel",
"author_id": 172710,
"author_profile": "https://wordpress.stackexchange.com/users/172710",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to get custom taxonomy comma separated listing than we can go with WordPress inbuilt function <a href=\"https://codex.wordpress.org/Function_Reference/get_the_term_list\" rel=\"nofollow noreferrer\"><code>get_the_term_list()</code></a></p>\n\n<pre><code>get_the_term_list( $id, $taxonomy, $before, $sep, $after )\n$id : Post ID\n$taxonomy : Name of taxonomy\n$before : Leading text\n$sep : String to separate tags\n$after : Trailing text\n\nfor example,\n<?php echo get_the_term_list( $post->ID, 'people', 'People: ', ', ' ); ?>\n</code></pre>\n\n<p>or we can go with </p>\n\n<pre><code>$term_obj_list = get_the_terms( $post->ID, 'taxonomy' );\n$terms_string = join(', ', wp_list_pluck($term_obj_list, 'name'));\n\n</code></pre>\n"
},
{
"answer_id": 357344,
"author": "divyaT",
"author_id": 177804,
"author_profile": "https://wordpress.stackexchange.com/users/177804",
"pm_score": 2,
"selected": true,
"text": "<p>From your explanation above I understood that you want to show custom taxonomy you have registered for that post type. </p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_category/\" rel=\"nofollow noreferrer\">the_category()</a>; fetches the default category that comes with the default post.</p>\n\n<p>For rendering custom taxonomy you need to add something like this:</p>\n\n<pre><code>$terms = get_the_terms( $post->ID , 'your custom taxonomy slug' );\nforeach ( $terms as $term ) {\n echo $term->name;\n}\n</code></pre>\n"
}
] | 2020/01/28 | [
"https://wordpress.stackexchange.com/questions/357309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | I have a custom post type that I'm importing into the front page of the site with `WP_Query()`, but I can't seem to get the custom taxonomy to show.
I've placed a div in the HTML and inside this I'm calling `the_category()`, but nothing is being outputted to the front end.
The taxonomy is showing in the back end and I've added a custom taxonomy (category) to all of the three posts I want to show.
```
<?php
$homePageNews = new WP_Query(array(
'posts_per_page' => 3,
'post_type'=> 'news'
));
while($homePageNews->have_posts()){
$homePageNews->the_post(); ?>
<article class="article top-article lastest-top-article">
<?php the_post_thumbnail('post-thumbnail',
['class' => 'image latest-top-image hover-class']); ?>
<div class="cat"><?php the_category( ', ' ); ?></div>
<div class="content-wrapper content-wrapper-mobile-padding">
<h3 class="td no-bottom-margin hover-class"><a class="top-latest-heading" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<hr>
<p><?php the_content(); ?></h3></p>
</div>
</article>
<?php } ?>
<?php wp_reset_postdata(); ?>
``` | From your explanation above I understood that you want to show custom taxonomy you have registered for that post type.
[the\_category()](https://developer.wordpress.org/reference/functions/the_category/); fetches the default category that comes with the default post.
For rendering custom taxonomy you need to add something like this:
```
$terms = get_the_terms( $post->ID , 'your custom taxonomy slug' );
foreach ( $terms as $term ) {
echo $term->name;
}
``` |
357,312 | <p>So I've been messing with this for a while now and I don't understand how I'm unable to pull in my style file properly by registering and calling it at all.</p>
<p>Here is my method:</p>
<pre><code>public static function register_styles()
{
add_action('wp_enqueue_scripts', function() {
global $post;
if (is_page('foodies')) {
var_dump('Hello!');
//Adding stylesheets
wp_register_style('profile-style', '/Users/smajlovs/Sites/newsacfoodies/htdocs/wp-content/mu-plugins/sacfoodies/styles/style.css');
//Enqueue the style
wp_enqueue_style('profile-style', '/Users/smajlovs/Sites/newsacfoodies/htdocs/wp-content/mu-plugins/sacfoodies/styles/style.css');
}
if ($post->post_type == 'profile') {
echo 'Hello! I am the register_styles method on the profile custom post type page';
}
return;
});
}
</code></pre>
<p>Within my main sacfoodies.php file, I'm calling <code>Profile::register_styles()</code>.</p>
<hr>
<p>The confusing part is, the <code>var_dump</code> that I have inside that function actually dumps out the hello on that page as shown here:</p>
<p><code>var_dump(wp_enqueue_style('profile-style'));</code> returns null</p>
<p>So does anyone know why my enqueue register and call won't render my style.css file? I have the absolute path in there for testing purposes and nothing.</p>
| [
{
"answer_id": 357314,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 2,
"selected": true,
"text": "<p>Call like this. It may be help you.</p>\n\n<pre><code>wp_register_style('profile-style',content_url().'/mu-plugins/sacfoodies/styles/style.css');\nwp_enqueue_style('profile-style');\n</code></pre>\n"
},
{
"answer_id": 357323,
"author": "Dip Patel",
"author_id": 172710,
"author_profile": "https://wordpress.stackexchange.com/users/172710",
"pm_score": 1,
"selected": false,
"text": "<p>If we getting expected result up to <strong>var_dump('Hello!');</strong> than can we replace below 2 lines as following..</p>\n\n<pre><code>wp_register_style('profile-style', WPMU_PLUGIN_URL.'/sacfoodies/styles/style.css');\nwp_enqueue_style('profile-style');\n</code></pre>\n\n<p>let me know reflected changes....</p>\n\n<p>Thank you</p>\n"
},
{
"answer_id": 357328,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 0,
"selected": false,
"text": "<p>Something like this should work</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'enqueue_styles' );\nfunction enqueue_styles() {\n\nif ( is_page('foodies') ) {\n\n wp_enqueue_style( 'your-styles', get_stylesheet_directory_uri() . '/css/style.css' );\n }\n}\n</code></pre>\n\n<p>Swap out the <code>get_stylesheet_directory_uri() . '/css/style.css'</code> to match the path to your style sheet.</p>\n"
},
{
"answer_id": 400740,
"author": "Sebas Rossi",
"author_id": 140364,
"author_profile": "https://wordpress.stackexchange.com/users/140364",
"pm_score": 0,
"selected": false,
"text": "<p>This is my solution, it works both on post and pages.\nHope it helps:</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_styles' );\n\nfunction my_theme_styles() {\n if( get_queried_object_id() == 460 ) {\n wp_register_style( 'my-styles', get_stylesheet_directory_uri() . '/my-styles.css');\n wp_enqueue_style( 'my-styles', get_stylesheet_directory_uri() . '/my-styles.css');\n\n }\n}\n</code></pre>\n<p>460 is the ID of a post / page</p>\n"
}
] | 2020/01/28 | [
"https://wordpress.stackexchange.com/questions/357312",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | So I've been messing with this for a while now and I don't understand how I'm unable to pull in my style file properly by registering and calling it at all.
Here is my method:
```
public static function register_styles()
{
add_action('wp_enqueue_scripts', function() {
global $post;
if (is_page('foodies')) {
var_dump('Hello!');
//Adding stylesheets
wp_register_style('profile-style', '/Users/smajlovs/Sites/newsacfoodies/htdocs/wp-content/mu-plugins/sacfoodies/styles/style.css');
//Enqueue the style
wp_enqueue_style('profile-style', '/Users/smajlovs/Sites/newsacfoodies/htdocs/wp-content/mu-plugins/sacfoodies/styles/style.css');
}
if ($post->post_type == 'profile') {
echo 'Hello! I am the register_styles method on the profile custom post type page';
}
return;
});
}
```
Within my main sacfoodies.php file, I'm calling `Profile::register_styles()`.
---
The confusing part is, the `var_dump` that I have inside that function actually dumps out the hello on that page as shown here:
`var_dump(wp_enqueue_style('profile-style'));` returns null
So does anyone know why my enqueue register and call won't render my style.css file? I have the absolute path in there for testing purposes and nothing. | Call like this. It may be help you.
```
wp_register_style('profile-style',content_url().'/mu-plugins/sacfoodies/styles/style.css');
wp_enqueue_style('profile-style');
``` |
357,332 | <p>I have a JSON file stored in my child theme directory: file.json). Separately, the PHP template for my page contains some JavaScript code (in the form of a <code><script></code> tag). In that JS code, I want to write the contents of the JSON file to a variable. What is the proper approach to this?</p>
<ul>
<li>Can/should I enqueue the JSON file, just as I would a normal JS file (i.e. <code>wp_enqueue_scripts()</code>)? If so, how would I in-turn write the contents of the file to a JS variable? Would I do something like <code>myJson = json.parse('http://example.com/wp-contents/themes/your-theme/file.json'</code>)?</li>
<li>Can I just use <code>include</code> to include the JSON file on the page? Actually now that I think about it, one can only use <code>include</code> with certain file extensions--correct?</li>
<li>Should I perhaps use PHP to save the contents of the JSON file to a PHP variable, then pass that variable to the JS code?</li>
</ul>
<p>Thanks in advance.</p>
| [
{
"answer_id": 357314,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 2,
"selected": true,
"text": "<p>Call like this. It may be help you.</p>\n\n<pre><code>wp_register_style('profile-style',content_url().'/mu-plugins/sacfoodies/styles/style.css');\nwp_enqueue_style('profile-style');\n</code></pre>\n"
},
{
"answer_id": 357323,
"author": "Dip Patel",
"author_id": 172710,
"author_profile": "https://wordpress.stackexchange.com/users/172710",
"pm_score": 1,
"selected": false,
"text": "<p>If we getting expected result up to <strong>var_dump('Hello!');</strong> than can we replace below 2 lines as following..</p>\n\n<pre><code>wp_register_style('profile-style', WPMU_PLUGIN_URL.'/sacfoodies/styles/style.css');\nwp_enqueue_style('profile-style');\n</code></pre>\n\n<p>let me know reflected changes....</p>\n\n<p>Thank you</p>\n"
},
{
"answer_id": 357328,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 0,
"selected": false,
"text": "<p>Something like this should work</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'enqueue_styles' );\nfunction enqueue_styles() {\n\nif ( is_page('foodies') ) {\n\n wp_enqueue_style( 'your-styles', get_stylesheet_directory_uri() . '/css/style.css' );\n }\n}\n</code></pre>\n\n<p>Swap out the <code>get_stylesheet_directory_uri() . '/css/style.css'</code> to match the path to your style sheet.</p>\n"
},
{
"answer_id": 400740,
"author": "Sebas Rossi",
"author_id": 140364,
"author_profile": "https://wordpress.stackexchange.com/users/140364",
"pm_score": 0,
"selected": false,
"text": "<p>This is my solution, it works both on post and pages.\nHope it helps:</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_styles' );\n\nfunction my_theme_styles() {\n if( get_queried_object_id() == 460 ) {\n wp_register_style( 'my-styles', get_stylesheet_directory_uri() . '/my-styles.css');\n wp_enqueue_style( 'my-styles', get_stylesheet_directory_uri() . '/my-styles.css');\n\n }\n}\n</code></pre>\n<p>460 is the ID of a post / page</p>\n"
}
] | 2020/01/28 | [
"https://wordpress.stackexchange.com/questions/357332",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51204/"
] | I have a JSON file stored in my child theme directory: file.json). Separately, the PHP template for my page contains some JavaScript code (in the form of a `<script>` tag). In that JS code, I want to write the contents of the JSON file to a variable. What is the proper approach to this?
* Can/should I enqueue the JSON file, just as I would a normal JS file (i.e. `wp_enqueue_scripts()`)? If so, how would I in-turn write the contents of the file to a JS variable? Would I do something like `myJson = json.parse('http://example.com/wp-contents/themes/your-theme/file.json'`)?
* Can I just use `include` to include the JSON file on the page? Actually now that I think about it, one can only use `include` with certain file extensions--correct?
* Should I perhaps use PHP to save the contents of the JSON file to a PHP variable, then pass that variable to the JS code?
Thanks in advance. | Call like this. It may be help you.
```
wp_register_style('profile-style',content_url().'/mu-plugins/sacfoodies/styles/style.css');
wp_enqueue_style('profile-style');
``` |
357,342 | <p><a href="https://developer.wordpress.org/reference/hooks/the_author/" rel="nofollow noreferrer"><code>the_author()</code> filter hook</a> can be used to modify the output of <code>the_author()</code>. When using the hook, is it possible to know which PHP file generates which call to <code>the_author()</code>?</p>
<p>For example, say I have this custom function attached to <code>the_author()</code> filter hook, which modifies <code>the_author()</code> output:</p>
<pre><code>add_filter("the_author", "change_author");
function change_author($author) {
$author = "NEW AUTHOR!";
return $author;
}
</code></pre>
<p>When I load my page, I can see this change occur in 5 separate sections:</p>
<ul>
<li>Once in the header (from file header.php).</li>
<li>Twice in the body (from file page.php).</li>
<li>Twice in the footer (from file footer.php).</li>
</ul>
<p>Inside my function <code>change_author()</code>, is there any way to know which PHP file is currently making the call to <code>the_author()</code>?</p>
<p>My motivation for asking is because I'd like to change the author for only certain sections, i.e. only when <code>the_author()</code> is called from a specific file (my_file.php). For all other instances of the <code>the_author()</code> I want to leave the output unmolested. I'm just wondering if that's possible to accomplish using <code>the_author()</code> filter hook.</p>
| [
{
"answer_id": 357314,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 2,
"selected": true,
"text": "<p>Call like this. It may be help you.</p>\n\n<pre><code>wp_register_style('profile-style',content_url().'/mu-plugins/sacfoodies/styles/style.css');\nwp_enqueue_style('profile-style');\n</code></pre>\n"
},
{
"answer_id": 357323,
"author": "Dip Patel",
"author_id": 172710,
"author_profile": "https://wordpress.stackexchange.com/users/172710",
"pm_score": 1,
"selected": false,
"text": "<p>If we getting expected result up to <strong>var_dump('Hello!');</strong> than can we replace below 2 lines as following..</p>\n\n<pre><code>wp_register_style('profile-style', WPMU_PLUGIN_URL.'/sacfoodies/styles/style.css');\nwp_enqueue_style('profile-style');\n</code></pre>\n\n<p>let me know reflected changes....</p>\n\n<p>Thank you</p>\n"
},
{
"answer_id": 357328,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 0,
"selected": false,
"text": "<p>Something like this should work</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'enqueue_styles' );\nfunction enqueue_styles() {\n\nif ( is_page('foodies') ) {\n\n wp_enqueue_style( 'your-styles', get_stylesheet_directory_uri() . '/css/style.css' );\n }\n}\n</code></pre>\n\n<p>Swap out the <code>get_stylesheet_directory_uri() . '/css/style.css'</code> to match the path to your style sheet.</p>\n"
},
{
"answer_id": 400740,
"author": "Sebas Rossi",
"author_id": 140364,
"author_profile": "https://wordpress.stackexchange.com/users/140364",
"pm_score": 0,
"selected": false,
"text": "<p>This is my solution, it works both on post and pages.\nHope it helps:</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_styles' );\n\nfunction my_theme_styles() {\n if( get_queried_object_id() == 460 ) {\n wp_register_style( 'my-styles', get_stylesheet_directory_uri() . '/my-styles.css');\n wp_enqueue_style( 'my-styles', get_stylesheet_directory_uri() . '/my-styles.css');\n\n }\n}\n</code></pre>\n<p>460 is the ID of a post / page</p>\n"
}
] | 2020/01/28 | [
"https://wordpress.stackexchange.com/questions/357342",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51204/"
] | [`the_author()` filter hook](https://developer.wordpress.org/reference/hooks/the_author/) can be used to modify the output of `the_author()`. When using the hook, is it possible to know which PHP file generates which call to `the_author()`?
For example, say I have this custom function attached to `the_author()` filter hook, which modifies `the_author()` output:
```
add_filter("the_author", "change_author");
function change_author($author) {
$author = "NEW AUTHOR!";
return $author;
}
```
When I load my page, I can see this change occur in 5 separate sections:
* Once in the header (from file header.php).
* Twice in the body (from file page.php).
* Twice in the footer (from file footer.php).
Inside my function `change_author()`, is there any way to know which PHP file is currently making the call to `the_author()`?
My motivation for asking is because I'd like to change the author for only certain sections, i.e. only when `the_author()` is called from a specific file (my\_file.php). For all other instances of the `the_author()` I want to leave the output unmolested. I'm just wondering if that's possible to accomplish using `the_author()` filter hook. | Call like this. It may be help you.
```
wp_register_style('profile-style',content_url().'/mu-plugins/sacfoodies/styles/style.css');
wp_enqueue_style('profile-style');
``` |
357,397 | <p><a href="https://i.stack.imgur.com/PIxfV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PIxfV.png" alt="which plugin is this"></a></p>
<p>i want to know which plugin is this or similar types of plugin <a href="https://www.variyoshop.com/product/free-fire-diamond-direct-from-player-id-top-up/" rel="nofollow noreferrer">https://www.variyoshop.com/product/free-fire-diamond-direct-from-player-id-top-up/</a></p>
| [
{
"answer_id": 357314,
"author": "Tanmay Patel",
"author_id": 62026,
"author_profile": "https://wordpress.stackexchange.com/users/62026",
"pm_score": 2,
"selected": true,
"text": "<p>Call like this. It may be help you.</p>\n\n<pre><code>wp_register_style('profile-style',content_url().'/mu-plugins/sacfoodies/styles/style.css');\nwp_enqueue_style('profile-style');\n</code></pre>\n"
},
{
"answer_id": 357323,
"author": "Dip Patel",
"author_id": 172710,
"author_profile": "https://wordpress.stackexchange.com/users/172710",
"pm_score": 1,
"selected": false,
"text": "<p>If we getting expected result up to <strong>var_dump('Hello!');</strong> than can we replace below 2 lines as following..</p>\n\n<pre><code>wp_register_style('profile-style', WPMU_PLUGIN_URL.'/sacfoodies/styles/style.css');\nwp_enqueue_style('profile-style');\n</code></pre>\n\n<p>let me know reflected changes....</p>\n\n<p>Thank you</p>\n"
},
{
"answer_id": 357328,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 0,
"selected": false,
"text": "<p>Something like this should work</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'enqueue_styles' );\nfunction enqueue_styles() {\n\nif ( is_page('foodies') ) {\n\n wp_enqueue_style( 'your-styles', get_stylesheet_directory_uri() . '/css/style.css' );\n }\n}\n</code></pre>\n\n<p>Swap out the <code>get_stylesheet_directory_uri() . '/css/style.css'</code> to match the path to your style sheet.</p>\n"
},
{
"answer_id": 400740,
"author": "Sebas Rossi",
"author_id": 140364,
"author_profile": "https://wordpress.stackexchange.com/users/140364",
"pm_score": 0,
"selected": false,
"text": "<p>This is my solution, it works both on post and pages.\nHope it helps:</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_styles' );\n\nfunction my_theme_styles() {\n if( get_queried_object_id() == 460 ) {\n wp_register_style( 'my-styles', get_stylesheet_directory_uri() . '/my-styles.css');\n wp_enqueue_style( 'my-styles', get_stylesheet_directory_uri() . '/my-styles.css');\n\n }\n}\n</code></pre>\n<p>460 is the ID of a post / page</p>\n"
}
] | 2020/01/29 | [
"https://wordpress.stackexchange.com/questions/357397",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181771/"
] | [](https://i.stack.imgur.com/PIxfV.png)
i want to know which plugin is this or similar types of plugin <https://www.variyoshop.com/product/free-fire-diamond-direct-from-player-id-top-up/> | Call like this. It may be help you.
```
wp_register_style('profile-style',content_url().'/mu-plugins/sacfoodies/styles/style.css');
wp_enqueue_style('profile-style');
``` |
357,415 | <p>I'm trying to get a list of categories if they are used in a Custom Post type. The post type uses the default categories taxonomy. There are also other custom post types that use the same default WP category.</p>
<p>Is it possible to add a meta_query that checks if the category is used in a Custom post_type? eq: custom post type: work.</p>
<pre><code>$work_categorys = get_terms(
[
'taxonomy' => "category",
'hide_empty' => true,
]
);
foreach ($work_categorys as $key => $value) { echo '<li data-filter-tag="'.$value->slug.'" class="">'.$value->name.'</li>'; }
</code></pre>
| [
{
"answer_id": 357420,
"author": "Greg Winiarski",
"author_id": 154460,
"author_profile": "https://wordpress.stackexchange.com/users/154460",
"pm_score": 0,
"selected": false,
"text": "<p>To get all terms from all taxonomies assigned to \"work\" custom post type you can customize your code to look like this</p>\n\n<pre><code>$taxes = array_keys( get_object_taxonomies( 'work', 'objects' ) );\n$work_categorys = get_terms(\n [ \n 'taxonomy' => $taxes, \n 'hide_empty' => true,\n ]\n);\n</code></pre>\n"
},
{
"answer_id": 357424,
"author": "AnotherAccount",
"author_id": 162982,
"author_profile": "https://wordpress.stackexchange.com/users/162982",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/#comment-2500\" rel=\"nofollow noreferrer\">This would work.</a> As posted by <a href=\"https://profiles.wordpress.org/bucketpress/\" rel=\"nofollow noreferrer\">@bucketpress</a>.</p>\n\n<pre><code>$someposts = get_posts(\n array(\n 'post_type' => 'work',\n 'posts_per_page' => -1,\n 'fields' => 'ids', // return an array of ids\n )\n);\n\n$somepoststerms = get_terms(\n array(\n 'taxonomy' => 'category',\n 'object_ids' => $someposts,\n 'hide_empty' => true,\n )\n);\n</code></pre>\n"
}
] | 2020/01/29 | [
"https://wordpress.stackexchange.com/questions/357415",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97361/"
] | I'm trying to get a list of categories if they are used in a Custom Post type. The post type uses the default categories taxonomy. There are also other custom post types that use the same default WP category.
Is it possible to add a meta\_query that checks if the category is used in a Custom post\_type? eq: custom post type: work.
```
$work_categorys = get_terms(
[
'taxonomy' => "category",
'hide_empty' => true,
]
);
foreach ($work_categorys as $key => $value) { echo '<li data-filter-tag="'.$value->slug.'" class="">'.$value->name.'</li>'; }
``` | [This would work.](https://developer.wordpress.org/reference/classes/wp_term_query/__construct/#comment-2500) As posted by [@bucketpress](https://profiles.wordpress.org/bucketpress/).
```
$someposts = get_posts(
array(
'post_type' => 'work',
'posts_per_page' => -1,
'fields' => 'ids', // return an array of ids
)
);
$somepoststerms = get_terms(
array(
'taxonomy' => 'category',
'object_ids' => $someposts,
'hide_empty' => true,
)
);
``` |
357,465 | <p>I have a malware java script that was added to the end of every post. I tried using an SQL statement in phpMyAdmin. Here is a shortened version of that:</p>
<pre><code>SET @virus = "<script>var _0x2cf4=['MSIE"+CHAR(59)+"','OPR','Chromium','Chrome','ppkcookie','location','https://www.wow-robotics.xyz','onload','getElementById'...(and a lot more obfuscated script)...;
UPDATE
wp_posts
SET
post_content =
REPLACE
(
post_content,
@virus COLLATE utf8mb4_unicode_520_ci,
''
);
</code></pre>
<p>This was not initially successful because many false matches caused deletions all over the website. I didn't have time to find out why, so I shortened the search text to be only the beginning of the script, which broke the malware and rendered it merely ugly. This got me out of trouble, but obviously it's not the best solution.</p>
<p>How should I do this? I have tried to tokenize the post content, using the text of the malware script as the token:</p>
<pre><code><?php
ignore_user_abort(true);
set_time_limit(30);
$path = $_SERVER['DOCUMENT_ROOT'];
require( $path.'/wp-load.php' );
$post_table = $wpdb->prefix . 'posts';
$meta_table = $wpdb->prefix . 'postmeta';
$starting_virus_text = "<script>['MSIE;','OPR','Chromium','Chrome','ppkcookie','location','https://www.wow-robotics.xy";
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$posts = get_posts($args);
echo 'Post count is '.count($posts).'<br>';
foreach($posts as $post){
$new_content = strtok($post->post_content, $starting_virus_text);
if ($post->ID == 192) { // my home page, just for example
echo 'POST 192<br><pre>';
var_dump($post->post_content);
}
if (strlen($new_content) > 20){
echo $new_content;
die;
}
}
echo '<br>Done.';
?>
</code></pre>
<p>This was also unsuccessful. The token is never found in the post content, even though it is there. Should I do a character-ny-character type examination and store post_content in an intermediate variable? Any advice is appreciated.</p>
| [
{
"answer_id": 357420,
"author": "Greg Winiarski",
"author_id": 154460,
"author_profile": "https://wordpress.stackexchange.com/users/154460",
"pm_score": 0,
"selected": false,
"text": "<p>To get all terms from all taxonomies assigned to \"work\" custom post type you can customize your code to look like this</p>\n\n<pre><code>$taxes = array_keys( get_object_taxonomies( 'work', 'objects' ) );\n$work_categorys = get_terms(\n [ \n 'taxonomy' => $taxes, \n 'hide_empty' => true,\n ]\n);\n</code></pre>\n"
},
{
"answer_id": 357424,
"author": "AnotherAccount",
"author_id": 162982,
"author_profile": "https://wordpress.stackexchange.com/users/162982",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/#comment-2500\" rel=\"nofollow noreferrer\">This would work.</a> As posted by <a href=\"https://profiles.wordpress.org/bucketpress/\" rel=\"nofollow noreferrer\">@bucketpress</a>.</p>\n\n<pre><code>$someposts = get_posts(\n array(\n 'post_type' => 'work',\n 'posts_per_page' => -1,\n 'fields' => 'ids', // return an array of ids\n )\n);\n\n$somepoststerms = get_terms(\n array(\n 'taxonomy' => 'category',\n 'object_ids' => $someposts,\n 'hide_empty' => true,\n )\n);\n</code></pre>\n"
}
] | 2020/01/29 | [
"https://wordpress.stackexchange.com/questions/357465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122051/"
] | I have a malware java script that was added to the end of every post. I tried using an SQL statement in phpMyAdmin. Here is a shortened version of that:
```
SET @virus = "<script>var _0x2cf4=['MSIE"+CHAR(59)+"','OPR','Chromium','Chrome','ppkcookie','location','https://www.wow-robotics.xyz','onload','getElementById'...(and a lot more obfuscated script)...;
UPDATE
wp_posts
SET
post_content =
REPLACE
(
post_content,
@virus COLLATE utf8mb4_unicode_520_ci,
''
);
```
This was not initially successful because many false matches caused deletions all over the website. I didn't have time to find out why, so I shortened the search text to be only the beginning of the script, which broke the malware and rendered it merely ugly. This got me out of trouble, but obviously it's not the best solution.
How should I do this? I have tried to tokenize the post content, using the text of the malware script as the token:
```
<?php
ignore_user_abort(true);
set_time_limit(30);
$path = $_SERVER['DOCUMENT_ROOT'];
require( $path.'/wp-load.php' );
$post_table = $wpdb->prefix . 'posts';
$meta_table = $wpdb->prefix . 'postmeta';
$starting_virus_text = "<script>['MSIE;','OPR','Chromium','Chrome','ppkcookie','location','https://www.wow-robotics.xy";
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$posts = get_posts($args);
echo 'Post count is '.count($posts).'<br>';
foreach($posts as $post){
$new_content = strtok($post->post_content, $starting_virus_text);
if ($post->ID == 192) { // my home page, just for example
echo 'POST 192<br><pre>';
var_dump($post->post_content);
}
if (strlen($new_content) > 20){
echo $new_content;
die;
}
}
echo '<br>Done.';
?>
```
This was also unsuccessful. The token is never found in the post content, even though it is there. Should I do a character-ny-character type examination and store post\_content in an intermediate variable? Any advice is appreciated. | [This would work.](https://developer.wordpress.org/reference/classes/wp_term_query/__construct/#comment-2500) As posted by [@bucketpress](https://profiles.wordpress.org/bucketpress/).
```
$someposts = get_posts(
array(
'post_type' => 'work',
'posts_per_page' => -1,
'fields' => 'ids', // return an array of ids
)
);
$somepoststerms = get_terms(
array(
'taxonomy' => 'category',
'object_ids' => $someposts,
'hide_empty' => true,
)
);
``` |
357,522 | <p>I'm looking for a way to load my JavaScript and CSS only on the product page, but only if it's a Variable Products.</p>
<p>The <code>is_product()</code> function works well, but my scripts are loaded for all types of products: Simple, Variable, Grouped .....</p>
<p>How to limit the loading of scripts only for a variable product?</p>
| [
{
"answer_id": 357420,
"author": "Greg Winiarski",
"author_id": 154460,
"author_profile": "https://wordpress.stackexchange.com/users/154460",
"pm_score": 0,
"selected": false,
"text": "<p>To get all terms from all taxonomies assigned to \"work\" custom post type you can customize your code to look like this</p>\n\n<pre><code>$taxes = array_keys( get_object_taxonomies( 'work', 'objects' ) );\n$work_categorys = get_terms(\n [ \n 'taxonomy' => $taxes, \n 'hide_empty' => true,\n ]\n);\n</code></pre>\n"
},
{
"answer_id": 357424,
"author": "AnotherAccount",
"author_id": 162982,
"author_profile": "https://wordpress.stackexchange.com/users/162982",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/#comment-2500\" rel=\"nofollow noreferrer\">This would work.</a> As posted by <a href=\"https://profiles.wordpress.org/bucketpress/\" rel=\"nofollow noreferrer\">@bucketpress</a>.</p>\n\n<pre><code>$someposts = get_posts(\n array(\n 'post_type' => 'work',\n 'posts_per_page' => -1,\n 'fields' => 'ids', // return an array of ids\n )\n);\n\n$somepoststerms = get_terms(\n array(\n 'taxonomy' => 'category',\n 'object_ids' => $someposts,\n 'hide_empty' => true,\n )\n);\n</code></pre>\n"
}
] | 2020/01/30 | [
"https://wordpress.stackexchange.com/questions/357522",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65465/"
] | I'm looking for a way to load my JavaScript and CSS only on the product page, but only if it's a Variable Products.
The `is_product()` function works well, but my scripts are loaded for all types of products: Simple, Variable, Grouped .....
How to limit the loading of scripts only for a variable product? | [This would work.](https://developer.wordpress.org/reference/classes/wp_term_query/__construct/#comment-2500) As posted by [@bucketpress](https://profiles.wordpress.org/bucketpress/).
```
$someposts = get_posts(
array(
'post_type' => 'work',
'posts_per_page' => -1,
'fields' => 'ids', // return an array of ids
)
);
$somepoststerms = get_terms(
array(
'taxonomy' => 'category',
'object_ids' => $someposts,
'hide_empty' => true,
)
);
``` |
357,529 | <p>I need to add the filter option on search page in wordpress site.
Created dropdown with two options. one is 'Recently Added' and 'Last Updated'.
We need to filter the courses by selecting dropdown.</p>
<p>I have created dropdown and written jquery to hook the filter using ajax call method.
Created filter.php file and hook the pre_get_posts method inside this file.
If we select the dropdown it need to hook that filter but it is not get hooked.
Also i have tried to Pass the parameter via ajax call but it's not working.
Please share ideas to achieve the filter options.</p>
<p><strong>HTML</strong></p>
<pre><code><select id="filter">
<option value='last_updated_posts' id='recently_added'>
Last Updated
</option>
<option value="recently_added_posts" id='last_updated'>
Recently Added
</option>
</select>
</code></pre>
<p><strong>Custom.js</strong></p>
<pre><code> jQuery("#filter").change(function(){
var selected_option=jQuery("#filter option:selected").val();
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {'action' :selected_option },
success: function(response){alert(response);}
});
});
</code></pre>
<p><strong>filter.php</strong></p>
<pre><code><?php
add_action('wp_ajax_recently_added_posts', 'recently_added_posts');
add_action('wp_ajax_nopriv_recently_added_posts', 'recently_added_posts');
if($_POST['action'] =='recently_added_posts' ){
function recently_added_posts($query) {
if ($query->is_search() && !is_admin() ) {
$query->set('post_type',array('sfwd-courses','sfwd-lessons','sfwd-topic'));
$query->set('orderby',array(
'post_type'=> 'ASC',
'date' => 'DESC')
);
return $query;
die();
}
add_filter('pre_get_posts','recently_added_posts');
}
}
add_action('wp_ajax_last_updated_posts', 'last_updated_posts');
add_action('wp_ajax_nopriv_last_updated_posts', 'last_updated_posts');
if($_POST['action'] =='last_updated_posts' ){
function last_updated_posts($query) {
if ($query->is_search() && !is_admin() ) {
$query->set('post_type',array('sfwd-courses','sfwd-lessons','sfwd-topic'));
$query->set('orderby',array(
'post_type'=> 'ASC',
'modified' => 'DESC')
);
}
return $query;
die();
}
add_filter('pre_get_posts','last_updated_posts');
}
function ajaxurl_filter() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'ajaxurl_filter');
?>
</code></pre>
<p>Thanks in advance!</p>
| [
{
"answer_id": 357546,
"author": "Waldo Rabie",
"author_id": 172667,
"author_profile": "https://wordpress.stackexchange.com/users/172667",
"pm_score": 0,
"selected": false,
"text": "<p>You're not actually executing a new WP_Query so no results are being returned. Try this...</p>\n\n<pre><code><?php\nadd_action('wp_ajax_recently_added_posts', 'recently_added_posts');\n\nif ($_POST['action'] =='recently_added_posts' ) {\n function recently_added_posts( $query ) {\n // Setup query\n global $wp_query;\n\n // Define arguments\n $query_args = array( \n 'post_type' => array( \n 'sfwd-courses', \n 'sfwd-lessons', \n 'sfwd-topic' ),\n 'orderby' => array(\n 'post_type'=> 'ASC',\n 'date' => 'DESC'\n ),\n 'posts_per_page' => 10, // (change if needed)\n\n );\n\n $wp_query = new WP_Query($query_args);\n\n // You can then loop through the posts in your themes template file\n // NOTE: may need to play around this but if you just return the query you'll see all the posts in the front end\n $_template_file = THEME_DIR . 'search.php';\n load_template( $_template_file, $require_once = true );\n\n die();\n }\n\n // This will now work because the query was instantiated...\n add_filter('pre_get_posts','recently_added_posts'); \n}\n?>\n</code></pre>\n"
},
{
"answer_id": 375262,
"author": "Amin",
"author_id": 113633,
"author_profile": "https://wordpress.stackexchange.com/users/113633",
"pm_score": 1,
"selected": false,
"text": "<p>You can apply a custom filter on your WP_Query that is on your ajax callback function like this:</p>\n<pre><code>$my_query = apply_filters('my_plugin_pre_get_posts', (new WP_Query($args)));\n</code></pre>\n<p>Now you can use your existing <code>pre_get_posts</code> function for ajax calls also,</p>\n<pre><code>add_action('pre_get_posts', 'myplugin_filter_posts'); // For All WP_Query instances\nadd_filter('my_plugin_pre_get_posts', 'myplugin_filter_posts'); // For ajax\n\nfunction myplugin_filter_posts($query) {\n if (defined('DOING_AJAX') && DOING_AJAX) {\n // Your code executed only on ajax requests\n }\n\n // Codes here Execute everywhere\n\n return $query; // Return $query is required for the filter we defined\n}\n</code></pre>\n<p>You can tweak it to achieve what you wish</p>\n"
}
] | 2020/01/30 | [
"https://wordpress.stackexchange.com/questions/357529",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/181872/"
] | I need to add the filter option on search page in wordpress site.
Created dropdown with two options. one is 'Recently Added' and 'Last Updated'.
We need to filter the courses by selecting dropdown.
I have created dropdown and written jquery to hook the filter using ajax call method.
Created filter.php file and hook the pre\_get\_posts method inside this file.
If we select the dropdown it need to hook that filter but it is not get hooked.
Also i have tried to Pass the parameter via ajax call but it's not working.
Please share ideas to achieve the filter options.
**HTML**
```
<select id="filter">
<option value='last_updated_posts' id='recently_added'>
Last Updated
</option>
<option value="recently_added_posts" id='last_updated'>
Recently Added
</option>
</select>
```
**Custom.js**
```
jQuery("#filter").change(function(){
var selected_option=jQuery("#filter option:selected").val();
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {'action' :selected_option },
success: function(response){alert(response);}
});
});
```
**filter.php**
```
<?php
add_action('wp_ajax_recently_added_posts', 'recently_added_posts');
add_action('wp_ajax_nopriv_recently_added_posts', 'recently_added_posts');
if($_POST['action'] =='recently_added_posts' ){
function recently_added_posts($query) {
if ($query->is_search() && !is_admin() ) {
$query->set('post_type',array('sfwd-courses','sfwd-lessons','sfwd-topic'));
$query->set('orderby',array(
'post_type'=> 'ASC',
'date' => 'DESC')
);
return $query;
die();
}
add_filter('pre_get_posts','recently_added_posts');
}
}
add_action('wp_ajax_last_updated_posts', 'last_updated_posts');
add_action('wp_ajax_nopriv_last_updated_posts', 'last_updated_posts');
if($_POST['action'] =='last_updated_posts' ){
function last_updated_posts($query) {
if ($query->is_search() && !is_admin() ) {
$query->set('post_type',array('sfwd-courses','sfwd-lessons','sfwd-topic'));
$query->set('orderby',array(
'post_type'=> 'ASC',
'modified' => 'DESC')
);
}
return $query;
die();
}
add_filter('pre_get_posts','last_updated_posts');
}
function ajaxurl_filter() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'ajaxurl_filter');
?>
```
Thanks in advance! | You can apply a custom filter on your WP\_Query that is on your ajax callback function like this:
```
$my_query = apply_filters('my_plugin_pre_get_posts', (new WP_Query($args)));
```
Now you can use your existing `pre_get_posts` function for ajax calls also,
```
add_action('pre_get_posts', 'myplugin_filter_posts'); // For All WP_Query instances
add_filter('my_plugin_pre_get_posts', 'myplugin_filter_posts'); // For ajax
function myplugin_filter_posts($query) {
if (defined('DOING_AJAX') && DOING_AJAX) {
// Your code executed only on ajax requests
}
// Codes here Execute everywhere
return $query; // Return $query is required for the filter we defined
}
```
You can tweak it to achieve what you wish |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.