qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
259,657 | <p>I'm building a plugin using the <a href="https://github.com/DevinVinson/WordPress-Plugin-Boilerplate" rel="nofollow noreferrer">WordPress Plugin Boilerplate by DevinVinson</a>.</p>
<p>Everything works fine, except one thing:</p>
<p>I'm trying to enqueue scripts and css only when a shortcode is present in the page. </p>
<p>In <code>define_public_hooks</code> function, I added a call to the loader to register scripts instead of enqueuing them:</p>
<pre><code>private function define_public_hooks() {
// ...
$this->loader->add_action( 'wp_register_script', $plugin_public, 'register_styles' );
$this->loader->add_action( 'wp_register_script', $plugin_public, 'register_scripts' );
// ...
}
</code></pre>
<p>Then in <code>class-my-plugin-public.php</code> file I created two public functions <code>register_styles()</code> and <code>register_scripts()</code>. Inside these functions, I just register scripts and styles, instead of enqueuing them. It's something basic, like this:</p>
<pre><code>public function register_scripts() {
wp_register_script( $this->plugin_name . '_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key .'&amp;v=3&amp;libraries=places', array( 'jquery' ), '3', true );
}
</code></pre>
<p>Then I would like to enqueue them in the shortcode return function, but they do not get registered at all.</p>
<p>I checked with <code>wp_script_is( $this->plugin_name . '_google_maps_api', 'registered' )</code>, and it returns <code>false</code>.</p>
<p>If I make the very same stuff, but with <code>enqueue</code> instead of <code>register</code> everything works fine.</p>
<p>Any idea why?</p>
| [
{
"answer_id": 259662,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 0,
"selected": false,
"text": "<p>So the problem is that the first argument to the <code>add_action</code> call needs to be a <em>WordPress</e... | 2017/03/10 | [
"https://wordpress.stackexchange.com/questions/259657",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4155/"
] | I'm building a plugin using the [WordPress Plugin Boilerplate by DevinVinson](https://github.com/DevinVinson/WordPress-Plugin-Boilerplate).
Everything works fine, except one thing:
I'm trying to enqueue scripts and css only when a shortcode is present in the page.
In `define_public_hooks` function, I added a call to the loader to register scripts instead of enqueuing them:
```
private function define_public_hooks() {
// ...
$this->loader->add_action( 'wp_register_script', $plugin_public, 'register_styles' );
$this->loader->add_action( 'wp_register_script', $plugin_public, 'register_scripts' );
// ...
}
```
Then in `class-my-plugin-public.php` file I created two public functions `register_styles()` and `register_scripts()`. Inside these functions, I just register scripts and styles, instead of enqueuing them. It's something basic, like this:
```
public function register_scripts() {
wp_register_script( $this->plugin_name . '_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key .'&v=3&libraries=places', array( 'jquery' ), '3', true );
}
```
Then I would like to enqueue them in the shortcode return function, but they do not get registered at all.
I checked with `wp_script_is( $this->plugin_name . '_google_maps_api', 'registered' )`, and it returns `false`.
If I make the very same stuff, but with `enqueue` instead of `register` everything works fine.
Any idea why? | Why it's not working:
=====================
You need to use the [`wp_enqueue_scripts`](https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/) action hook. You've used `wp_register_script` as an action hook, however, there is no action hook named `wp_register_script` in WordPress core.
If this was just a silly mistake, then you already have the answer. Read on if you need more information regarding the topic:
---
Attaching a callback function to [`wp_enqueue_scripts`](https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/) [action hook](https://developer.wordpress.org/plugins/hooks/actions/) doesn't mean your scripts and styles will be enqueued, it simply means when you want to execute that [callback function](http://php.net/manual/en/language.types.callable.php).
The original registering and enqueuing is done by functions such as: `wp_register_script()`, `wp_register_style`, `wp_enqueue_script()`, `wp_enqueue_style()` etc., not by any [hook](https://developer.wordpress.org/plugins/hooks/).
>
> Note the difference between the role of functions and hooks:
>
>
> * A [**function**](http://php.net/manual/en/functions.user-defined.php) executes some CODE to accomplish predefined tasks when called.
>
>
> Example: these all are WordPress core functions: `wp_register_script()`, `wp_register_style`, `wp_enqueue_script()`, `wp_enqueue_style()`.
> * A [**hook**](https://developer.wordpress.org/plugins/hooks/) only attaches a [callable](http://php.net/manual/en/function.is-callable.php) function (to be executed later) at a predefined point of CODE execution.
>
>
> Example: this is a WordPress core (action) hook: `wp_enqueue_scripts` - notice the `s` (plural) at the end.
>
>
> ***Double check:*** `wp_enqueue_script()` is a function and `wp_enqueue_scripts` is an action hook.
>
>
>
The correct CODE:
=================
So your corrected CODE should be like:
```
private function define_public_hooks() {
// ...
$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'register_styles' );
$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'register_scripts' );
// ...
}
```
Then,
```
public function register_scripts() {
wp_register_script( $this->plugin_name . '_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key.'&v=3&libraries=places', array( 'jquery' ), '3', true );
}
```
After that, you enqueue the script (& style) from within you shortcode handler function:
```
public function your_shortcode_handler( $atts ) {
// shortcode related CODE
wp_enqueue_script( $this->plugin_name . '_google_maps_api' );
// more shortcode related CODE
}
```
With this CODE, your scripts / styles enqueued from `your_shortcode_handler` function will only be added to your site when there is a shortcode in that particular URL.
Further Reading:
----------------
[This answer](https://wordpress.stackexchange.com/a/165759/110572) has an interesting discussion on enqueuing scripts & styles only when shortcode is present. |
259,677 | <p>I am a WP beginner and am trying to upload a web module to a wordpress site. The site is a landing page, and a link on the landing page leads to a demoable web app. The web app was custom written in HTML and JS and I need to upload those files to this route in the WP site.</p>
<p>Does anyone have any suggestions/insight/advice?</p>
<p>Thank you!</p>
| [
{
"answer_id": 259684,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 0,
"selected": false,
"text": "<p>Welcome to WordPress!</p>\n\n<p>Your best bet would be to setup a localhost server <a href=\"http://www.w... | 2017/03/11 | [
"https://wordpress.stackexchange.com/questions/259677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115201/"
] | I am a WP beginner and am trying to upload a web module to a wordpress site. The site is a landing page, and a link on the landing page leads to a demoable web app. The web app was custom written in HTML and JS and I need to upload those files to this route in the WP site.
Does anyone have any suggestions/insight/advice?
Thank you! | All you need to do is create a custom page for your theme. Here is a very brief example:
Create a file called: page-example.php
```
<?php
/*
Template Name: Example Page
*/
?>
<?php get_header(); ?>
The html code will go here. Don't add the <head> or <body> info.
<?php get_footer(); ?>
```
The next thing to do is add the following to your functions.php file:
```
function load_example_scripts() {
wp_enqueue_script('moment', get_stylesheet_directory_uri() . '/js/example.js');
}
add_action( 'wp_enqueue_scripts', 'load_example_scripts' );
```
Now upload the page-example.php to your main template folder (where header.php, footer.php, functions.php are)
I usually add a folder to my themes named "JS" and put all jquery scripts there. So upload the example.js file to the "JS" folder of your theme.
Finally, go to the wordpress admin, and edit the page where you want this to appear and on the side menu under "templates", select "example".
I would have to see the exact code to give you more help, but that is the basic idea. |
259,707 | <p>I want to add image from post content in my rss feed but all the tutorials that I find are only for featured image. I want image from post content and not featured image. How can I do this?</p>
| [
{
"answer_id": 259708,
"author": "shpwebhost",
"author_id": 114992,
"author_profile": "https://wordpress.stackexchange.com/users/114992",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to use content images on other website or pages you may use WordPress REST API. This will h... | 2017/03/11 | [
"https://wordpress.stackexchange.com/questions/259707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100682/"
] | I want to add image from post content in my rss feed but all the tutorials that I find are only for featured image. I want image from post content and not featured image. How can I do this? | Here is the [link](http://wpcodesnippet.com/display-featured-post-thumbnails-wordpress-feeds/) I found a solution. How to display featured post thumbnails in WordPress feeds
paste this code snippet in your theme functions.php file
```
// display featured post thumbnails in WordPress feeds
function wcs_post_thumbnails_in_feeds( $content ) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
//if you want to show thumbnail image
$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</figure>' . $content;
// if you want to show full image
//$content = '<p>' . get_the_post_thumbnail( $post->ID,'full' ) . '</p>' . $content;
//if you want to custom image using add_image_size()
//$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'custom-image-size' ) . '</figure>' . $content;
}
return $content;
}
add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );
```
This is the concepts how to you show external link image. How you fetch the external image, it upon you.
it's showing all the post same image. Just change image link for each post.
ex: src="'.$image\_url.'"
```
function rss_feed_from_external_link( $content ) {
global $post;
$content = '<figure><img width="150" height="128" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" class="attachment-thumbnail size-thumbnail wp-post-image" alt="" sizes="100vw" /></figure>' . $content;
return $content;
}
add_filter( 'the_excerpt_rss', 'rss_feed_from_external_link' );
add_filter( 'the_content_feed', 'rss_feed_from_external_link' );
```
Image showing for custom field.
```
add_filter('the_content', 'custom_fields_for_feeds');
add_filter('the_meta','custom_files_for_feed');
function custom_fields_for_feeds( $content ) {
global $post;
global $post;
// Get the custom fields ***
// Checks for thumbnail
$image = get_post_meta($post->ID, 'Thumbnail', $single = true);
// Checks for thumbnail alt text
$image_alt = get_post_meta($post->ID, 'Thumbnail Alt', $single = true);
if($image_alt == '') { $image_alt = 'This image has no alt text'; }
if($image !== '') {
$content = '<figure><img src="'.$image.'" alt="'.$image_alt.'" /></figure>' . $content;
return $content;
}
else {
$content = $content;
return $content;
}
add_filter('the_content', 'custom_fields_for_feeds');
add_filter('the_meta','custom_files_for_feed');
```
You can also use custom image fields to display in the RSS feed.
Let me know you not solve your problem. |
259,713 | <p>As everyone might be aware that there are many wordpress website builders in the market, Can anyone explain me whats the real difference between Theme Builders and Page Builders? I looked up in google but couldn't find the answer to it.</p>
| [
{
"answer_id": 259708,
"author": "shpwebhost",
"author_id": 114992,
"author_profile": "https://wordpress.stackexchange.com/users/114992",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to use content images on other website or pages you may use WordPress REST API. This will h... | 2017/03/11 | [
"https://wordpress.stackexchange.com/questions/259713",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115217/"
] | As everyone might be aware that there are many wordpress website builders in the market, Can anyone explain me whats the real difference between Theme Builders and Page Builders? I looked up in google but couldn't find the answer to it. | Here is the [link](http://wpcodesnippet.com/display-featured-post-thumbnails-wordpress-feeds/) I found a solution. How to display featured post thumbnails in WordPress feeds
paste this code snippet in your theme functions.php file
```
// display featured post thumbnails in WordPress feeds
function wcs_post_thumbnails_in_feeds( $content ) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
//if you want to show thumbnail image
$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</figure>' . $content;
// if you want to show full image
//$content = '<p>' . get_the_post_thumbnail( $post->ID,'full' ) . '</p>' . $content;
//if you want to custom image using add_image_size()
//$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'custom-image-size' ) . '</figure>' . $content;
}
return $content;
}
add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );
```
This is the concepts how to you show external link image. How you fetch the external image, it upon you.
it's showing all the post same image. Just change image link for each post.
ex: src="'.$image\_url.'"
```
function rss_feed_from_external_link( $content ) {
global $post;
$content = '<figure><img width="150" height="128" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" class="attachment-thumbnail size-thumbnail wp-post-image" alt="" sizes="100vw" /></figure>' . $content;
return $content;
}
add_filter( 'the_excerpt_rss', 'rss_feed_from_external_link' );
add_filter( 'the_content_feed', 'rss_feed_from_external_link' );
```
Image showing for custom field.
```
add_filter('the_content', 'custom_fields_for_feeds');
add_filter('the_meta','custom_files_for_feed');
function custom_fields_for_feeds( $content ) {
global $post;
global $post;
// Get the custom fields ***
// Checks for thumbnail
$image = get_post_meta($post->ID, 'Thumbnail', $single = true);
// Checks for thumbnail alt text
$image_alt = get_post_meta($post->ID, 'Thumbnail Alt', $single = true);
if($image_alt == '') { $image_alt = 'This image has no alt text'; }
if($image !== '') {
$content = '<figure><img src="'.$image.'" alt="'.$image_alt.'" /></figure>' . $content;
return $content;
}
else {
$content = $content;
return $content;
}
add_filter('the_content', 'custom_fields_for_feeds');
add_filter('the_meta','custom_files_for_feed');
```
You can also use custom image fields to display in the RSS feed.
Let me know you not solve your problem. |
259,716 | <p>When I call <a href="https://developer.wordpress.org/reference/functions/get_search_form" rel="nofollow noreferrer"><code>get_search_form()</code></a>, it outputs:</p>
<pre><code><form class="search-form">
<meta itemprop="target">
<input type="search">
<input type="submit">
</form>
</code></pre>
<p>But I wanted it to generate with a <code>span</code> inside, like:</p>
<pre><code><form class="search-form">
<meta itemprop="target">
<input type="search">
<span class="submit-icon"></span>
<input type="submit">
</form>
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 259717,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 2,
"selected": false,
"text": "<p>Tested and worked fine.</p>\n\n<p>Add this code in functions.php, You will get what you want. Now you ... | 2017/03/11 | [
"https://wordpress.stackexchange.com/questions/259716",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115077/"
] | When I call [`get_search_form()`](https://developer.wordpress.org/reference/functions/get_search_form), it outputs:
```
<form class="search-form">
<meta itemprop="target">
<input type="search">
<input type="submit">
</form>
```
But I wanted it to generate with a `span` inside, like:
```
<form class="search-form">
<meta itemprop="target">
<input type="search">
<span class="submit-icon"></span>
<input type="submit">
</form>
```
Any ideas? | If we look at the source code of [`get_search_form()`](https://developer.wordpress.org/reference/functions/get_search_form/), notice that before the form gets rendered, the `search_form_format` filter hook gets fired. We can use that to add another filter attached to `get_search_form` where the callback is dependent upon the format.
```
add_filter( 'search_form_format', 'wpse_259716_search_form_format', 99, 1 );
function wpse_259716_search_form_format( $format ) {
if( in_array( $format, array( 'xhtml', 'html5' ) ) ) {
add_filter( 'get_search_form', "wpse_259716_get_search_form_$format", 99, 1 );
}
return $format;
}
function wpse_259716_get_search_form_xhtml( $form ) {
$search = '<input type="submit"';
$xhtml = 'some xhtml';
$replace = $xhtml . $search;
return str_replace( $search, $replace, $form );
}
function wpse_259716_get_search_form_html5( $form ) {
$search = '<input type="submit"';
$html5 = 'some html5';
$replace = $html5 . $search;
return str_replace( $search, $replace, $form );
}
```
Alternatively, you could use a class-based approach.
```
$wpse_259716 = new wpse_259716();
add_filter( 'search_form_format', array( $wpse_259716, 'search_form_format' ), 99, 1 );
add_filter( 'get_search_form', array( $wpse_259716, 'get_search_form' ), 99, 1 );
class wpse_259716 {
protected $format;
public function search_form_format( $format ) {
return $this->format = $format;
}
public function get_search_form( $form ) {
$search = $replace = '<input type="submit"';
if( 'xhtml' === $this->format ) {
$xhtml = 'some xhtml';
$replace = $xhmtl . $search;
}
elseif( 'html5' === $this->format ) {
$html5 = 'some html5';
$replace = $html5 . $search;
}
return str_replace( $search, $replace, $form );
}
}
``` |
259,811 | <p>I have recently setup a Linode Apache2 Debian server and I am hosting my WordPress site on it. It seems I can only connect to the server with SFTP.</p>
<p>When I attempt to add/update a plugin I am presented with this screen:</p>
<p><a href="https://i.stack.imgur.com/oSyRL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oSyRL.png" alt="enter image description here"></a></p>
<p>There doesn't appear to be an option to use SFTP instead of FTP or FTPS. I cannot find any plugins or anything to do this.</p>
<p>Because of this, I cannot add/update plugins.</p>
<p>What are my options?</p>
| [
{
"answer_id": 259857,
"author": "geraldo",
"author_id": 38096,
"author_profile": "https://wordpress.stackexchange.com/users/38096",
"pm_score": 1,
"selected": false,
"text": "<p>I use <a href=\"https://wordpress.org/plugins/ssh-sftp-updater-support/\" rel=\"nofollow noreferrer\">SSH SFT... | 2017/03/12 | [
"https://wordpress.stackexchange.com/questions/259811",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86794/"
] | I have recently setup a Linode Apache2 Debian server and I am hosting my WordPress site on it. It seems I can only connect to the server with SFTP.
When I attempt to add/update a plugin I am presented with this screen:
[](https://i.stack.imgur.com/oSyRL.png)
There doesn't appear to be an option to use SFTP instead of FTP or FTPS. I cannot find any plugins or anything to do this.
Because of this, I cannot add/update plugins.
What are my options? | Looks like a permissions issue:
```
sudo chown -R www-data:www-data /var/www
``` |
259,834 | <p>I've followed all the steps for migrating my existing wordpress site to another server. However, when I try to login to the migrated site, it keeps redirecting me to the old one, despite whether I use wp-admin.php or wp-login.php.</p>
<p>I have also read about a dozen different pages on migrating worpress accounts, but not one of them encounters the problems I am having with some of the steps.</p>
<p>These are the steps I have followed, including differences I am encountering with those specified on migration instructions (problems highlighted in bold):</p>
<p>1) Downloaded all wordpress files from oldsite to my hard drive using ftp.</p>
<p>2) Downloaded the database from my oldsite using PHP myadmin.</p>
<p>3) Uploaded all the wordpress files to a chosen directory on my newsite using ftp.</p>
<p>4) Created a new database on the newsite using PHP Myadmin. <strong>As I am loading onto a different server, I created a new database using the same database name and password from the oldsite. That way I didn't have to change the WPconfig file. Is that okay to do? Not a single migration article I read used the same database and password, nor did they say not to, so I assumed it would be okay.</strong></p>
<p>5) Used phpMyadmin to change the database entry in wp_options to the new URL. <strong>However, every instruction I read says there are two fields to change: siteurl and home. There is no home field in my wp-options. Just siteurl.</strong></p>
<p>6) I used the following string entered into SQL in phpMyadmin to change all the oldsite urls to the newsite url successfully:</p>
<p>update wp_posts set post_content = replace(
post_content, '<a href="http://oldsite/" rel="nofollow noreferrer">http://oldsite/</a>',
'<a href="http://newsite/" rel="nofollow noreferrer">http://newsite/</a>');</p>
<p>Did the same for all these database tables:</p>
<p>wp_posts
wp_redirection_logs
wp_users
wp_redirection_items</p>
<p>I checked each table and all of the changes were fine.</p>
<p>7) Checked every database table to make sure there were no instances of the oldsite URL. Could not find one.</p>
<p>8)Entered newsite URL into browser. <strong>I get a 404 message. The menu, latest postings and banner all appear okay, but if I hover over any of them they are all pointing to the oldsite URLs.</strong></p>
<p><strong>9)When I try to get into the admin panel of the newsite, it allows me to enter the name and password, then automatically redirects me to the oldsite and asks me to login again. Tried on different browsers but the results are always the same.</strong></p>
<p>Any ideas what I'm doing wrong?</p>
| [
{
"answer_id": 259836,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>First make sure that your wp-config file you've got is connected to the right database.</p>\n\n<p>You need to ... | 2017/03/13 | [
"https://wordpress.stackexchange.com/questions/259834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115295/"
] | I've followed all the steps for migrating my existing wordpress site to another server. However, when I try to login to the migrated site, it keeps redirecting me to the old one, despite whether I use wp-admin.php or wp-login.php.
I have also read about a dozen different pages on migrating worpress accounts, but not one of them encounters the problems I am having with some of the steps.
These are the steps I have followed, including differences I am encountering with those specified on migration instructions (problems highlighted in bold):
1) Downloaded all wordpress files from oldsite to my hard drive using ftp.
2) Downloaded the database from my oldsite using PHP myadmin.
3) Uploaded all the wordpress files to a chosen directory on my newsite using ftp.
4) Created a new database on the newsite using PHP Myadmin. **As I am loading onto a different server, I created a new database using the same database name and password from the oldsite. That way I didn't have to change the WPconfig file. Is that okay to do? Not a single migration article I read used the same database and password, nor did they say not to, so I assumed it would be okay.**
5) Used phpMyadmin to change the database entry in wp\_options to the new URL. **However, every instruction I read says there are two fields to change: siteurl and home. There is no home field in my wp-options. Just siteurl.**
6) I used the following string entered into SQL in phpMyadmin to change all the oldsite urls to the newsite url successfully:
update wp\_posts set post\_content = replace(
post\_content, '<http://oldsite/>',
'<http://newsite/>');
Did the same for all these database tables:
wp\_posts
wp\_redirection\_logs
wp\_users
wp\_redirection\_items
I checked each table and all of the changes were fine.
7) Checked every database table to make sure there were no instances of the oldsite URL. Could not find one.
8)Entered newsite URL into browser. **I get a 404 message. The menu, latest postings and banner all appear okay, but if I hover over any of them they are all pointing to the oldsite URLs.**
**9)When I try to get into the admin panel of the newsite, it allows me to enter the name and password, then automatically redirects me to the oldsite and asks me to login again. Tried on different browsers but the results are always the same.**
Any ideas what I'm doing wrong? | Try to add the following two lines in `wp-config.php` file:
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
``` |
259,839 | <p>I decided to integrate several standalone WordPress websites into a single Multisite installation.</p>
<p>I created a brand new Multisite install with subdomains, created a MU network site with subdomain URL, and exported the content from the original standalone site, then imported that content into the subdomain MU site. I then deleted the original standalone site from cPanel, and set the MU site's domain name to the original domain name.</p>
<p>The main site loads fine now on its original domain name, but when I try to login to the subdomain site at <code>site.example.com/wp-admin/</code> (using the brand new multisite's network admin user credentials), I receive an error:</p>
<blockquote>
<p>ERROR: Cookies are blocked or not supported by your browser. You must
enable cookies to use WordPress.</p>
</blockquote>
<p>But cookies <em>are</em> enabled in Chrome.</p>
<p>I tried adding the following to <code>wp-config.php</code>:</p>
<pre><code>define('COOKIE_DOMAIN', false);
</code></pre>
<p>...but the issue remains.</p>
<p>The same issue occurs if I use WP Migrate DB Pro to pull in a standalone website into a MU subdomain site, then delete the standalone site from cPanel, and then set the MU subdomain site's domain to be the original standalone site's domain name... the site's frontend loads fine, but I just can't login to WP admin.</p>
| [
{
"answer_id": 260295,
"author": "Dean Jansen",
"author_id": 114897,
"author_profile": "https://wordpress.stackexchange.com/users/114897",
"pm_score": -1,
"selected": false,
"text": "<p>Please try adding the following to your wp-config.php file</p>\n\n<p>Also remove all cookies from your... | 2017/03/13 | [
"https://wordpress.stackexchange.com/questions/259839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
] | I decided to integrate several standalone WordPress websites into a single Multisite installation.
I created a brand new Multisite install with subdomains, created a MU network site with subdomain URL, and exported the content from the original standalone site, then imported that content into the subdomain MU site. I then deleted the original standalone site from cPanel, and set the MU site's domain name to the original domain name.
The main site loads fine now on its original domain name, but when I try to login to the subdomain site at `site.example.com/wp-admin/` (using the brand new multisite's network admin user credentials), I receive an error:
>
> ERROR: Cookies are blocked or not supported by your browser. You must
> enable cookies to use WordPress.
>
>
>
But cookies *are* enabled in Chrome.
I tried adding the following to `wp-config.php`:
```
define('COOKIE_DOMAIN', false);
```
...but the issue remains.
The same issue occurs if I use WP Migrate DB Pro to pull in a standalone website into a MU subdomain site, then delete the standalone site from cPanel, and then set the MU subdomain site's domain to be the original standalone site's domain name... the site's frontend loads fine, but I just can't login to WP admin. | First clear your browser's cache (including cookies), and your server's cache (e.g. cache plugins). Then set the following in your `wp-config.php` file:
```
define('ADMIN_COOKIE_PATH', '/');
define('COOKIE_DOMAIN', '');
define('COOKIEPATH', '');
define('SITECOOKIEPATH', '');
```
Also, you may checkout the [answer from HERE](https://community.bitnami.com/t/wp-multisite-multidomains-cookies-issue/46603):
```
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'example.com');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
define('SUNRISE', 'on');
```
If it still fails, then [read this answer](https://stackoverflow.com/a/21593484/7466542) or contact your server's support. There may be a configuration issue on the server. |
259,849 | <p>I try to order a WP_Query of a custom post type 'entry' by a meta value 'votes', but it keeps showing up ordered by date.
My code:</p>
<pre><code>$args = array(
'post_type' => 'entry',
'orderby' => 'votes',
'order' => 'DESC',
'posts_per_page' => 10,
'post_status' => 'publish'
);
$loop = new WP_Query($args);
</code></pre>
<p>When I evaluate <code>$loop->request</code> in xDebug, I get this, which indicates the results are indeed ordered by <code>post_date DESC</code>:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'entry' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
</code></pre>
<p>Do I need to use <code>meta_query</code> to order on custom post type meta fields? I thought that was only needed when you want to compare/restrict results based on custom meta?</p>
| [
{
"answer_id": 259851,
"author": "dhuyvetter",
"author_id": 86095,
"author_profile": "https://wordpress.stackexchange.com/users/86095",
"pm_score": 2,
"selected": false,
"text": "<p>OK, I figured it pour reading about <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.... | 2017/03/13 | [
"https://wordpress.stackexchange.com/questions/259849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86095/"
] | I try to order a WP\_Query of a custom post type 'entry' by a meta value 'votes', but it keeps showing up ordered by date.
My code:
```
$args = array(
'post_type' => 'entry',
'orderby' => 'votes',
'order' => 'DESC',
'posts_per_page' => 10,
'post_status' => 'publish'
);
$loop = new WP_Query($args);
```
When I evaluate `$loop->request` in xDebug, I get this, which indicates the results are indeed ordered by `post_date DESC`:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'entry' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
Do I need to use `meta_query` to order on custom post type meta fields? I thought that was only needed when you want to compare/restrict results based on custom meta? | OK, I figured it pour reading about [Orderby Parameters in WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters) more carefully. I needed to set `votes` to `meta_key` and `orderby` to `meta_value_num`:
```
$args = array(
'post_type' => 'entry',
'meta_key' => 'votes',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'posts_per_page' => 10,
'post_status' => 'publish'
);
$loop = new WP_Query($args);
``` |
259,883 | <p>I would like to overwrite some content which is located in (<code>inc/</code>) <code>template-tags.php</code> file on parent theme.</p>
<p>Content need to be changed is in function <code>footer_content_widget_area</code> in <code>template-tags.php</code> file and that function is called on <code>functions.php</code>:</p>
<pre><code>add_action( 'page_widgets', 'footer_content_widget_area' );
</code></pre>
| [
{
"answer_id": 260054,
"author": "Justin",
"author_id": 114945,
"author_profile": "https://wordpress.stackexchange.com/users/114945",
"pm_score": -1,
"selected": false,
"text": "<p>As long as you have a child-theme setup correctly then you just allow the child-theme to replace the parent... | 2017/03/13 | [
"https://wordpress.stackexchange.com/questions/259883",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92020/"
] | I would like to overwrite some content which is located in (`inc/`) `template-tags.php` file on parent theme.
Content need to be changed is in function `footer_content_widget_area` in `template-tags.php` file and that function is called on `functions.php`:
```
add_action( 'page_widgets', 'footer_content_widget_area' );
``` | In `functions.php` child theme include `template-tags.php` from parent theme:
```
require_once get_theme_file_path( '../parent-theme/inc/template-tags.php' );
```
In the child theme `template-tags.php` remove parent action and add the child action replacing it:
```
remove_action( 'tag', 'parent-function', 0 );
add_action( 'tag', 'new-child-function', 10 );
``` |
259,936 | <p>Having practised mirroring an existing wordpress site, I'm ready to migrate my website to a new server. Having simplified the steps necessary to do this, I'm hoping the following will work without having to change any database entries or Wordpress files. The domain name will stay the same, only the host will change.</p>
<p>1) Backup wordpress files from oldsite<br>
2) Back up database from oldsite<br>
3) Create a database on the new site using the same database name and password from the oldsite. (That way there is no need to change the original config file).<br>
4) Upload oldsite database into newsite database.<br>
5) Upload all wordpress files onto new server<br>
6) Have the DNS record of my domain changed to point to the new server and directory.<br>
7) Wait up to 48 hours (Although the TTL value is set to 10 minutes)<br>
8) Newsite should be working identically to the oldsite<br>
9) Delete all files from oldsite </p>
<p>Should this work okay? </p>
<p>My website is live and my main source of income. It also has good Google rankings which I have spent years achieving. My biggest fear is that by moving from one server to another Google will see it as a duplicate or brand new site and penalize me in the search results. I've also been told that all the Facebook likes on articles will break and will reset to zero. Is that correct?</p>
| [
{
"answer_id": 260054,
"author": "Justin",
"author_id": 114945,
"author_profile": "https://wordpress.stackexchange.com/users/114945",
"pm_score": -1,
"selected": false,
"text": "<p>As long as you have a child-theme setup correctly then you just allow the child-theme to replace the parent... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259936",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115295/"
] | Having practised mirroring an existing wordpress site, I'm ready to migrate my website to a new server. Having simplified the steps necessary to do this, I'm hoping the following will work without having to change any database entries or Wordpress files. The domain name will stay the same, only the host will change.
1) Backup wordpress files from oldsite
2) Back up database from oldsite
3) Create a database on the new site using the same database name and password from the oldsite. (That way there is no need to change the original config file).
4) Upload oldsite database into newsite database.
5) Upload all wordpress files onto new server
6) Have the DNS record of my domain changed to point to the new server and directory.
7) Wait up to 48 hours (Although the TTL value is set to 10 minutes)
8) Newsite should be working identically to the oldsite
9) Delete all files from oldsite
Should this work okay?
My website is live and my main source of income. It also has good Google rankings which I have spent years achieving. My biggest fear is that by moving from one server to another Google will see it as a duplicate or brand new site and penalize me in the search results. I've also been told that all the Facebook likes on articles will break and will reset to zero. Is that correct? | In `functions.php` child theme include `template-tags.php` from parent theme:
```
require_once get_theme_file_path( '../parent-theme/inc/template-tags.php' );
```
In the child theme `template-tags.php` remove parent action and add the child action replacing it:
```
remove_action( 'tag', 'parent-function', 0 );
add_action( 'tag', 'new-child-function', 10 );
``` |
259,942 | <p>Where is the value for <code>admin_email</code> set?</p>
<pre><code>$email = get_option('admin_email');
</code></pre>
<p>How can I change it?</p>
| [
{
"answer_id": 259944,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 3,
"selected": false,
"text": "<p>In Wordpress backend go to: <strong>Settings > General</strong> and the field <strong>'Email Address'</stron... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115340/"
] | Where is the value for `admin_email` set?
```
$email = get_option('admin_email');
```
How can I change it? | In Wordpress backend go to: **Settings > General** and the field **'Email Address'**.
Or in php: update\_option('admin\_email', 'your\_email@abc.com');
<https://codex.wordpress.org/Function_Reference/update_option> |
259,949 | <p>I wanted to exclude <code>pages</code> from the search results, and found many ways to do it, and was wondering why use <code>!is_admin()</code> or <code>is_main_query()</code> and which way would be better.</p>
<pre><code>add_filter('pre_get_posts','search_filter');
function search_filter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
</code></pre>
<hr>
<pre><code>add_filter('pre_get_posts','search_filter');
function search_filter($query) {
if ( !is_admin() && $query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
</code></pre>
<hr>
<pre><code>add_action('pre_get_posts','search_filter');
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
}
}
</code></pre>
| [
{
"answer_id": 259955,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 2,
"selected": false,
"text": "<p><code>pre_get_posts</code> will run in admin as well as the frontend, you can use it to filter posts that... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259949",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115018/"
] | I wanted to exclude `pages` from the search results, and found many ways to do it, and was wondering why use `!is_admin()` or `is_main_query()` and which way would be better.
```
add_filter('pre_get_posts','search_filter');
function search_filter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
```
---
```
add_filter('pre_get_posts','search_filter');
function search_filter($query) {
if ( !is_admin() && $query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
```
---
```
add_action('pre_get_posts','search_filter');
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
}
}
``` | Note that when we use:
```
$query->set( 'post_type', 'post' );
```
then we're overriding all searchable post types, not only the `page` post type.
That may be just fine in some cases, and we're done using some of your `pre_get_posts` snippets that fit our needs.
But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.
**Using the register\_post\_type\_args filter.**
When the post type isn't specified, the `WP_Query` search uses any post types that are searchable, [namely](https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264):
```
$in_search_post_types = get_post_types( array('exclude_from_search' => false) );
```
When we register a post type, we can set the `exclude_from_search` parameter as false to exclude it from search.
We can modify it for the `page` post type setup with:
```
add_filter( 'register_post_type_args', function( $args, $name )
{
// Target 'page' post type
if( 'page' === $name )
$args['exclude_from_search'] = true;
return $args;
}, 10, 2 );
```
More about `register_post_type()` [here](https://developer.wordpress.org/reference/functions/register_post_type/).
**Examples**
Here are examples where the page post type would be excluded from the search, using the above filtering:
* Main query search on the front-end with
```
https://example.tld?s=testing
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing' ] );
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );
```
**Some notes on queries with pre set post types:**
Let's consider cases where the post types are fixed, like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );
```
If the post type is set by some array `$post_type`, then we can filter the `'page'` out it with
```
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
}
```
If we don't have direct access to that array, we could use e.g. `pre_get_posts` to remove the 'page' from the post type array, with help of the `get`/`set` methods of `WP_Query`. Here's an example for the main search query on the front end:
```
add_action( 'pre_get_posts', function search_filter( \WP_Query $query )
{
if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )
return;
$post_type = $query->get( 'post_type' );
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
$query->set('post_type', $post_type );
}
} );
```
Why did we check the array count > 1 here?
That's because we should be careful to removing `'page'` from examples like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );
```
as an empty array or an empty string, for the post type:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );
```
will fall back to the `'post'` post type.
Note that:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );
```
isn't supported, as the resulting post type would be `'pagepost'`.
In these cases, where we don't have direct access to the `WP_Query` objects, we could halt the query with tricks like `'post__in' => []` or `1=0` in the search WHERE query part or even play with the `posts_pre_query` filter or using some more advanced methods. There are plenty of answers on this site about that. [This](https://wordpress.stackexchange.com/q/229722/26350) and [this](https://wordpress.stackexchange.com/q/226065/) is what I recall at the moment.
The `null` case:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );
```
falls back to `'any'` post types:
Hope it helps!
**PS:**
Also note the inconsistency in your snippets, as you have both
```
add_filter('pre_get_posts','search_filter');
```
and
```
add_action('pre_get_posts','search_filter');
```
It's considered an *action*, but it will not make any difference, as actions are wrapped as filters, behind the scenes. |
259,958 | <p>I'm building a function within functions.php</p>
<p>Within my function I want to make use of the post id of current post.
How do I do this?</p>
<p>The last thing I tried was this:</p>
<pre><code>global $post ;
$id = $post->id ;
</code></pre>
<p>However, this returns an empty string.</p>
| [
{
"answer_id": 259955,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 2,
"selected": false,
"text": "<p><code>pre_get_posts</code> will run in admin as well as the frontend, you can use it to filter posts that... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259958",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26187/"
] | I'm building a function within functions.php
Within my function I want to make use of the post id of current post.
How do I do this?
The last thing I tried was this:
```
global $post ;
$id = $post->id ;
```
However, this returns an empty string. | Note that when we use:
```
$query->set( 'post_type', 'post' );
```
then we're overriding all searchable post types, not only the `page` post type.
That may be just fine in some cases, and we're done using some of your `pre_get_posts` snippets that fit our needs.
But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.
**Using the register\_post\_type\_args filter.**
When the post type isn't specified, the `WP_Query` search uses any post types that are searchable, [namely](https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264):
```
$in_search_post_types = get_post_types( array('exclude_from_search' => false) );
```
When we register a post type, we can set the `exclude_from_search` parameter as false to exclude it from search.
We can modify it for the `page` post type setup with:
```
add_filter( 'register_post_type_args', function( $args, $name )
{
// Target 'page' post type
if( 'page' === $name )
$args['exclude_from_search'] = true;
return $args;
}, 10, 2 );
```
More about `register_post_type()` [here](https://developer.wordpress.org/reference/functions/register_post_type/).
**Examples**
Here are examples where the page post type would be excluded from the search, using the above filtering:
* Main query search on the front-end with
```
https://example.tld?s=testing
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing' ] );
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );
```
**Some notes on queries with pre set post types:**
Let's consider cases where the post types are fixed, like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );
```
If the post type is set by some array `$post_type`, then we can filter the `'page'` out it with
```
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
}
```
If we don't have direct access to that array, we could use e.g. `pre_get_posts` to remove the 'page' from the post type array, with help of the `get`/`set` methods of `WP_Query`. Here's an example for the main search query on the front end:
```
add_action( 'pre_get_posts', function search_filter( \WP_Query $query )
{
if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )
return;
$post_type = $query->get( 'post_type' );
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
$query->set('post_type', $post_type );
}
} );
```
Why did we check the array count > 1 here?
That's because we should be careful to removing `'page'` from examples like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );
```
as an empty array or an empty string, for the post type:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );
```
will fall back to the `'post'` post type.
Note that:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );
```
isn't supported, as the resulting post type would be `'pagepost'`.
In these cases, where we don't have direct access to the `WP_Query` objects, we could halt the query with tricks like `'post__in' => []` or `1=0` in the search WHERE query part or even play with the `posts_pre_query` filter or using some more advanced methods. There are plenty of answers on this site about that. [This](https://wordpress.stackexchange.com/q/229722/26350) and [this](https://wordpress.stackexchange.com/q/226065/) is what I recall at the moment.
The `null` case:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );
```
falls back to `'any'` post types:
Hope it helps!
**PS:**
Also note the inconsistency in your snippets, as you have both
```
add_filter('pre_get_posts','search_filter');
```
and
```
add_action('pre_get_posts','search_filter');
```
It's considered an *action*, but it will not make any difference, as actions are wrapped as filters, behind the scenes. |
259,970 | <p>i've got a question. I created a plugin with a menu and i want to show this under the Dashboard menu-item. In some of my wordpress installations the dashboard item will be overwrited. How can i fix this?</p>
<p>My code to add the menu is:</p>
<pre><code>add_menu_page('pluginname', 'pluginname', 'manage_options', 'pluginname-hello', '', 'dashicons-admin-site', 2);
</code></pre>
| [
{
"answer_id": 259955,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 2,
"selected": false,
"text": "<p><code>pre_get_posts</code> will run in admin as well as the frontend, you can use it to filter posts that... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259970",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115020/"
] | i've got a question. I created a plugin with a menu and i want to show this under the Dashboard menu-item. In some of my wordpress installations the dashboard item will be overwrited. How can i fix this?
My code to add the menu is:
```
add_menu_page('pluginname', 'pluginname', 'manage_options', 'pluginname-hello', '', 'dashicons-admin-site', 2);
``` | Note that when we use:
```
$query->set( 'post_type', 'post' );
```
then we're overriding all searchable post types, not only the `page` post type.
That may be just fine in some cases, and we're done using some of your `pre_get_posts` snippets that fit our needs.
But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.
**Using the register\_post\_type\_args filter.**
When the post type isn't specified, the `WP_Query` search uses any post types that are searchable, [namely](https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264):
```
$in_search_post_types = get_post_types( array('exclude_from_search' => false) );
```
When we register a post type, we can set the `exclude_from_search` parameter as false to exclude it from search.
We can modify it for the `page` post type setup with:
```
add_filter( 'register_post_type_args', function( $args, $name )
{
// Target 'page' post type
if( 'page' === $name )
$args['exclude_from_search'] = true;
return $args;
}, 10, 2 );
```
More about `register_post_type()` [here](https://developer.wordpress.org/reference/functions/register_post_type/).
**Examples**
Here are examples where the page post type would be excluded from the search, using the above filtering:
* Main query search on the front-end with
```
https://example.tld?s=testing
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing' ] );
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );
```
**Some notes on queries with pre set post types:**
Let's consider cases where the post types are fixed, like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );
```
If the post type is set by some array `$post_type`, then we can filter the `'page'` out it with
```
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
}
```
If we don't have direct access to that array, we could use e.g. `pre_get_posts` to remove the 'page' from the post type array, with help of the `get`/`set` methods of `WP_Query`. Here's an example for the main search query on the front end:
```
add_action( 'pre_get_posts', function search_filter( \WP_Query $query )
{
if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )
return;
$post_type = $query->get( 'post_type' );
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
$query->set('post_type', $post_type );
}
} );
```
Why did we check the array count > 1 here?
That's because we should be careful to removing `'page'` from examples like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );
```
as an empty array or an empty string, for the post type:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );
```
will fall back to the `'post'` post type.
Note that:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );
```
isn't supported, as the resulting post type would be `'pagepost'`.
In these cases, where we don't have direct access to the `WP_Query` objects, we could halt the query with tricks like `'post__in' => []` or `1=0` in the search WHERE query part or even play with the `posts_pre_query` filter or using some more advanced methods. There are plenty of answers on this site about that. [This](https://wordpress.stackexchange.com/q/229722/26350) and [this](https://wordpress.stackexchange.com/q/226065/) is what I recall at the moment.
The `null` case:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );
```
falls back to `'any'` post types:
Hope it helps!
**PS:**
Also note the inconsistency in your snippets, as you have both
```
add_filter('pre_get_posts','search_filter');
```
and
```
add_action('pre_get_posts','search_filter');
```
It's considered an *action*, but it will not make any difference, as actions are wrapped as filters, behind the scenes. |
259,985 | <p>I have tried is_front_page() but I believe that is the php way of doing it. Perhaps I'm not calling it right because, of course, I'm not getting a response. Maybe I'm just short of my detailed Js ways of accessing the Wordpress classes. </p>
<p>What I'm trying to do is simple. If I am on the front page or home page add this class if I'm not add this other class. Very simple it's just not working. I have even tried a pseudo span tag and add the class to that and it doesn't work. </p>
| [
{
"answer_id": 259986,
"author": "ferdouswp",
"author_id": 114362,
"author_profile": "https://wordpress.stackexchange.com/users/114362",
"pm_score": 0,
"selected": false,
"text": "<p>You can use page id class. If you add page-id class in your java script file maybe solve your problem. </... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259985",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64475/"
] | I have tried is\_front\_page() but I believe that is the php way of doing it. Perhaps I'm not calling it right because, of course, I'm not getting a response. Maybe I'm just short of my detailed Js ways of accessing the Wordpress classes.
What I'm trying to do is simple. If I am on the front page or home page add this class if I'm not add this other class. Very simple it's just not working. I have even tried a pseudo span tag and add the class to that and it doesn't work. | I just posted [an answer to another question](https://wordpress.stackexchange.com/a/259996/17305) about how to do it.
In your case, assuming you used `body_class()` in your theme, your home page should have a `<body>` with class `home` to it.
So in your JS, you can:
```
if( $('body.home').length ){
// Do stuff
}
``` |
259,987 | <p>I have this script that automatically scrolls down to the primary content on page load.</p>
<pre><code>jQuery(document).ready(function($){
if ( $(window).width() < 768 || window.Touch) {
$('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000);}
});
</code></pre>
<p><strong>1.</strong> However I would like to <em>only</em> apply it to our woocommerce product pages and categories so it doesnt work on home/blog pages. How would i do that? </p>
<p>I can do this <em>poorly</em> by editing WooCommerce core files but i know that's a horrible idea so I'm seeking out help on how to do it correctly via my functions.php file.</p>
<p><strong>2.</strong> Also i would like to know how to apply it to all pages except the home page should that be a better option later on.</p>
<p>Many thanks!</p>
| [
{
"answer_id": 259989,
"author": "Dragos Micu",
"author_id": 110131,
"author_profile": "https://wordpress.stackexchange.com/users/110131",
"pm_score": 2,
"selected": false,
"text": "<p>Step 1: save the code as a new js file, say main.js</p>\n\n<p>Step 2: add a conditional function to fun... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259987",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110570/"
] | I have this script that automatically scrolls down to the primary content on page load.
```
jQuery(document).ready(function($){
if ( $(window).width() < 768 || window.Touch) {
$('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000);}
});
```
**1.** However I would like to *only* apply it to our woocommerce product pages and categories so it doesnt work on home/blog pages. How would i do that?
I can do this *poorly* by editing WooCommerce core files but i know that's a horrible idea so I'm seeking out help on how to do it correctly via my functions.php file.
**2.** Also i would like to know how to apply it to all pages except the home page should that be a better option later on.
Many thanks! | There are two ways you could do that.
1. Using JS only
================
WordPress themes normally use the [`body_class()`](https://developer.wordpress.org/reference/functions/body_class/) function. As a result you'll see that the `<body>` tag will have lots of classes. You can then target pages with a specific class to run your code in JavaScript:
```
if( $('body.whateverclass').length || $('body.anotherclass').length ){
// Your JS code here
}
```
2. Using PHP
============
You can harness [`wp_localize_script()`](https://codex.wordpress.org/Function_Reference/wp_localize_script) to send a flag to your code.
Let's suppose you enqueued a file called `site.js` with a handle name of `site`, in your `functions.php` you'll have:
```
wp_register_script( 'site', 'path/to/site.js' );
wp_enqueue_script( 'site' );
```
You can now add some flags:
```
wp_register_script( 'site', 'path/to/site.js' ); # Unchanged
$value = '';
if ( is_shop() || is_some_other_condition() ){
$value = 'yes';
}
wp_localize_script( 'site', 'MYSITE', $value );
wp_enqueue_script( 'site' ); # Unchanged
```
You can then check the `MYSITE` variable in JavaScript:
```
if( 'yes' === MYSITE ){
// Your JS code here
}
```
Edit:
[You asked](https://wordpress.stackexchange.com/questions/259987/apply-jquery-script-to-only-woocommerce-product-pages-and-categories/259996#comment385846_259996) how to put it in the footer.php:
```
<script>
jQuery(document).ready(function($){
if( $('body.product-template-default').length || $('body.anotherclass').length ){
if ( $(window).width() < 768 || window.Touch) {
$('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000);
}
}
});
</script>
``` |
260,015 | <p>I am trying to make my own language switcher for my WordPress site. I am generating all labels using the <code>_e</code> and similar functions. So I am guessing the only thing I need to do is to change the locale used by WordPress. How can I do this programmatically?</p>
<p>So in the ideal scenario when a user clicks on the desired language "this code" is run and WordPress uses the corresponding <code>.mo</code> file for the translation.</p>
| [
{
"answer_id": 260096,
"author": "maxime schoeni",
"author_id": 81094,
"author_profile": "https://wordpress.stackexchange.com/users/81094",
"pm_score": 1,
"selected": false,
"text": "<p>Actually you need to hook in the 'locale' filter to set the language you want:</p>\n\n<pre><code>add_f... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112158/"
] | I am trying to make my own language switcher for my WordPress site. I am generating all labels using the `_e` and similar functions. So I am guessing the only thing I need to do is to change the locale used by WordPress. How can I do this programmatically?
So in the ideal scenario when a user clicks on the desired language "this code" is run and WordPress uses the corresponding `.mo` file for the translation. | Actually you need to hook in the 'locale' filter to set the language you want:
```
add_filter('locale', function($locale) {
return esc_attr($_GET['language']);
});
```
Then in the links of your switch, you need to pass the language variable:
```
<a href="<?php echo add_query_arg('language', 'xx_XX') ?>">XX</a>
```
Where xx\_XX is the language locale code for language XX |
260,021 | <p>I have a project where people can enter their details and only they can see those data by log in to there account.
Instead admin can see all data. </p>
<p>How can i achieve this using wordpress? please help me.</p>
| [
{
"answer_id": 260096,
"author": "maxime schoeni",
"author_id": 81094,
"author_profile": "https://wordpress.stackexchange.com/users/81094",
"pm_score": 1,
"selected": false,
"text": "<p>Actually you need to hook in the 'locale' filter to set the language you want:</p>\n\n<pre><code>add_f... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260021",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115393/"
] | I have a project where people can enter their details and only they can see those data by log in to there account.
Instead admin can see all data.
How can i achieve this using wordpress? please help me. | Actually you need to hook in the 'locale' filter to set the language you want:
```
add_filter('locale', function($locale) {
return esc_attr($_GET['language']);
});
```
Then in the links of your switch, you need to pass the language variable:
```
<a href="<?php echo add_query_arg('language', 'xx_XX') ?>">XX</a>
```
Where xx\_XX is the language locale code for language XX |
260,035 | <p>Please look at the picture below. I want to get <code>post_id</code> from <code>meta_value</code> = <strong>93</strong>. How can I do that?</p>
<p><a href="https://i.stack.imgur.com/Haekh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Haekh.png" alt=""></a></p>
| [
{
"answer_id": 260043,
"author": "Thilak",
"author_id": 113208,
"author_profile": "https://wordpress.stackexchange.com/users/113208",
"pm_score": 3,
"selected": false,
"text": "<p>Try this. It will work. </p>\n\n<pre><code>$prepare_guery = $wpdb->prepare( \"SELECT post_id FROM $wpdp-&... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77080/"
] | Please look at the picture below. I want to get `post_id` from `meta_value` = **93**. How can I do that?
[](https://i.stack.imgur.com/Haekh.png) | Try this. It will work.
```
$prepare_guery = $wpdb->prepare( "SELECT post_id FROM $wpdp->posts where meta_key ='_Wps_crossells' and meta_value like '%%d%'", $meta_value );
$get_values = $wpdb->get_col( $prepare_guery );
```
**Let me know it's working or not.** |
260,053 | <p>I want to offer my clients WordPress websites, but want to use WP multisite. I've read multiple articles on using a plugin, not using a plugin, etc. </p>
<p>My clients own their own domain names and want me to host/manage their sites. So I'll be using my main website as the install <code>abc.com</code>. </p>
<p>When you visit one of their sites like <code>client1.com</code> or <code>client2.com</code>, I don't want the domain name to be a subsite <code>client1.abc.com</code>. I need them to stay on <code>client1.com</code> or <code>client2.com</code>. </p>
<p>I did find a lot of tutorials, but most are with a plugin and some are reporting buggy behavior. </p>
<p>I've tried messing with the DNS as well, but the site still isn't redirecting. So I guess I'm just looking for the best way to do this. </p>
<p>Any and all help is appreciated.</p>
| [
{
"answer_id": 260186,
"author": "Justin",
"author_id": 114945,
"author_profile": "https://wordpress.stackexchange.com/users/114945",
"pm_score": 1,
"selected": false,
"text": "<p>To keep your options open with an open architecture you can create a multisite Network installation with mul... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260053",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44899/"
] | I want to offer my clients WordPress websites, but want to use WP multisite. I've read multiple articles on using a plugin, not using a plugin, etc.
My clients own their own domain names and want me to host/manage their sites. So I'll be using my main website as the install `abc.com`.
When you visit one of their sites like `client1.com` or `client2.com`, I don't want the domain name to be a subsite `client1.abc.com`. I need them to stay on `client1.com` or `client2.com`.
I did find a lot of tutorials, but most are with a plugin and some are reporting buggy behavior.
I've tried messing with the DNS as well, but the site still isn't redirecting. So I guess I'm just looking for the best way to do this.
Any and all help is appreciated. | To keep your options open with an open architecture you can create a multisite Network installation with multiple Networks. This means for each separate client you would give them a new Network. The advantage of this is that you can offer the scalability to Clients and keep your options open. Clients can easily have more sites (sub-domains) added to their Network.
structure would be
```
Network1 > abc.com (main site for the whole Wordpress Multi-Network install)
Network2 > client1.com
Network3 > client2.com
Network4 > client3.com
Network4 > client3.com/shop
```
this shows,
* Client1&2 have only one main site.
* Client3 has a main site "client3.com" and also one "client3.com/shop" subsite/sub-domain.
To make all this happen you need to install the plugin [wp-multi-network](https://wordpress.org/plugins/wp-multi-network/). Follow the install guidance for setup within wp-config.php for the plugin and
also add this to your wp-config.php file..
```
define( 'WP_HOME', '//' . $_SERVER['HTTP_HOST'] );
define( 'WP_SITEURL', '//' . $_SERVER['HTTP_HOST'] );
```
Be sure when you create your Wordpress Multi Network installation select "subfolder" install and not "subdomain" installation (refer to the codex [codex.wordpress.org/Create\_A\_Network](https://codex.wordpress.org/Create_A_Network)) and configure your sites for wordpress pretty permalinks (ref [codex.wordpress.org/Using\_Permalinks](https://codex.wordpress.org/Using_Permalinks)) |
260,070 | <p>I am trying to change pages when I search by category on my website. When I am not searching under a certain category I can switch pages fine but when I am searching for a category I am unable to switch pages. </p>
<pre><code>$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$orderby = ( get_query_var( 'orderby' ) ) ? absint( get_query_var( 'orderby' ) ) : 'display_name';
if($_GET['search'] && !empty($_GET['search'])) {
$search = $_GET['search'];
}
if($_GET['category'] && !empty($_GET['category'])) {
$category = $_GET['category'];
}
$args = array(
'orderby' => 'rand',
'number' => 7,
'paged' => $paged,
'search' => '*'.esc_attr( $search ).'*',
'meta_query' => array (
array(
'key' => 'organization_category_2',
'value' => $category,
'compare' => 'like'
)
)
);
$user_query = new WP_User_Query($args);
</code></pre>
<p>And my pagination links:</p>
<pre><code><?php
$total_user = $user_query->total_users;
$total_pages=ceil($total_user/7);
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '?paged=%#%',
'current' => $paged,
'total' => $total_pages,
'prev_text' => 'Previous',
'next_text' => 'Next',
'type' => 'list',
));
?>
</code></pre>
<p>Whenever I try and do a search I get a url like this:</p>
<p><code>https://mywebsite.ca/directory/?search&category=Government#038;category=Government&paged=2</code></p>
| [
{
"answer_id": 260072,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>The pagination functions work off of the main query, so you'd need to use <code>pre_get_posts</code> instead... | 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260070",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80568/"
] | I am trying to change pages when I search by category on my website. When I am not searching under a certain category I can switch pages fine but when I am searching for a category I am unable to switch pages.
```
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$orderby = ( get_query_var( 'orderby' ) ) ? absint( get_query_var( 'orderby' ) ) : 'display_name';
if($_GET['search'] && !empty($_GET['search'])) {
$search = $_GET['search'];
}
if($_GET['category'] && !empty($_GET['category'])) {
$category = $_GET['category'];
}
$args = array(
'orderby' => 'rand',
'number' => 7,
'paged' => $paged,
'search' => '*'.esc_attr( $search ).'*',
'meta_query' => array (
array(
'key' => 'organization_category_2',
'value' => $category,
'compare' => 'like'
)
)
);
$user_query = new WP_User_Query($args);
```
And my pagination links:
```
<?php
$total_user = $user_query->total_users;
$total_pages=ceil($total_user/7);
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '?paged=%#%',
'current' => $paged,
'total' => $total_pages,
'prev_text' => 'Previous',
'next_text' => 'Next',
'type' => 'list',
));
?>
```
Whenever I try and do a search I get a url like this:
`https://mywebsite.ca/directory/?search&category=Government#038;category=Government&paged=2` | The pagination functions work off of the main query, so you'd need to use `pre_get_posts` instead of creating a new query for them to work.
But, you're using `WP_User_Query`, so the standard pagination system will never work for you. You're going to have to 'roll your own' pagination system here, and generate your own URLs manually, and set the page yourself based on the URL |
260,083 | <p>How can I use <code>do_action</code> and <code>add_action</code> to return an array in <code>do_action</code>?</p>
<p>My sample code:</p>
<pre><code>function name_fun_one(){
$namearray[] = array('k1'=> 'text1', 'k2' => 'text1');
$namearray[] = array('k1'=> 'text2', 'k2' => 'text2');
do_action('add_in_namearray');
foreach($namearray as $val)
{
//loop
}
}
function add_name_fun_one()
{
$namearray[] = array('k1'=> 'text3', 'k2' => 'text3');
$namearray[] = array('k1'=> 'text4', 'k2' => 'text4');
}
add_action('name_fun_one', 'add_name_fun_one');
</code></pre>
| [
{
"answer_id": 260072,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>The pagination functions work off of the main query, so you'd need to use <code>pre_get_posts</code> instead... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115426/"
] | How can I use `do_action` and `add_action` to return an array in `do_action`?
My sample code:
```
function name_fun_one(){
$namearray[] = array('k1'=> 'text1', 'k2' => 'text1');
$namearray[] = array('k1'=> 'text2', 'k2' => 'text2');
do_action('add_in_namearray');
foreach($namearray as $val)
{
//loop
}
}
function add_name_fun_one()
{
$namearray[] = array('k1'=> 'text3', 'k2' => 'text3');
$namearray[] = array('k1'=> 'text4', 'k2' => 'text4');
}
add_action('name_fun_one', 'add_name_fun_one');
``` | The pagination functions work off of the main query, so you'd need to use `pre_get_posts` instead of creating a new query for them to work.
But, you're using `WP_User_Query`, so the standard pagination system will never work for you. You're going to have to 'roll your own' pagination system here, and generate your own URLs manually, and set the page yourself based on the URL |
260,095 | <p>I need to add a menu to a submenu in admin menu bar. Is it possible to do this in wordpress?</p>
<p>For Example :</p>
<pre><code>A
|
-> B
|
-> C
</code></pre>
<p>Or is there any work-around or hack to accomplish this?</p>
| [
{
"answer_id": 260104,
"author": "Savan Dholu",
"author_id": 108472,
"author_profile": "https://wordpress.stackexchange.com/users/108472",
"pm_score": 1,
"selected": false,
"text": "<p>No, it is not possible to create third level menu in admin panel. If you look at the definition of <str... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90559/"
] | I need to add a menu to a submenu in admin menu bar. Is it possible to do this in wordpress?
For Example :
```
A
|
-> B
|
-> C
```
Or is there any work-around or hack to accomplish this? | While the main admin menus (i.e., those on the left-hand side of the screen) can only be 2 deep (A > B), nodes in the [toolbar](https://codex.wordpress.org/Toolbar) can be arbitrarily deep.
I don't know if using the toolbar would be a suitable workaround for you, but if so, then you could do something like:
```
add_action ('wp_before_admin_bar_render', 'wpse_admin_toolbar_test') ;
function
admin_toolbar ()
{
global $wp_admin_bar ;
$args = array (
'id' => 'wpse_admin_toolbar_test',
'title' => 'WPSE Admin Toolbar Test',
) ;
$node = $wp_admin_bar->add_node ($args) ;
for ($i = 0 ; $i < 4 ; $i++) {
$args = array (
'id' => "wpse_admin_toolbar_test_item_{$i}",
'parent' => 'wpse_admin_toolbar_test',
'title' => "Item $i",
) ;
$wp_admin_bar->add_node ($args) ;
for ($y = 0 ; $y < 3 ; $y++) {
$args = array (
'id' => "wpse_admin_toolbar_test_item_{$i}_subitem_{$y}",
'parent' => "wpse_admin_toolbar_test_item_{$i}",
'title' => "Sub Item $y",
) ;
$wp_admin_bar->add_node ($args) ;
for ($z = 0 ; $z < 2 ; $z++) {
$args = array (
'id' => "wpse_admin_toolbar_test_item_{$i}_subitem_{$y}_subitem_{$z}",
'parent' => "wpse_admin_toolbar_test_item_{$i}_subitem_{$y}",
'title' => "Sub-Sub Item $z",
// in the real-world, this URL would be to something that
// would perform the action for this node
'href' => admin_url (),
) ;
$wp_admin_bar->add_node ($args) ;
}
}
}
return ;
}
```
The above would produce the following:
[](https://i.stack.imgur.com/TUQy8.png) |
260,105 | <p>This is a question I can't find the answer to:</p>
<p><strong>Can I run two separate Multisite networks under one domain?</strong></p>
<p>Here's the scenario, to better explain, we have a company website that already uses a WordPress Multisite network to run our country sites, like so:</p>
<pre><code>http://www.companysite.com/
http://www.companysite.com/fr/
http://www.companysite.com/se/
http://www.companysite.com/de/
http://www.companysite.com/jp/
http://www.companysite.com/cn/
etc.
</code></pre>
<p>All of these sites use the same theme, the same plugins, so it makes sense to run them off one network.</p>
<p>Then we have a bunch of separate "stand-alone" wordpress sites that are marketing "campaign"-based sites, each one unique, usually developed by 3rd parties, with their own themes and plugins, which run of sub-directories of the multisite installations:</p>
<pre><code>http://www.companysite.com/education
http://www.companysite.com/marketing
http://www.companysite.com/innovation
etc.
</code></pre>
<p>We don't really want to run them off the same Multisite installation because these use different themes and plugins, are written by 3rd parties, are subject to spikes due to marketing campaigns, and are less secure/stable than our country based sites network.</p>
<p>However, we do need them to be on the same domain...</p>
<p>Which brings me back to my original question:</p>
<p><strong>Can I run two separate Multisite networks under one domain?</strong></p>
<p>Thanks for reading!</p>
| [
{
"answer_id": 260109,
"author": "Sami",
"author_id": 102593,
"author_profile": "https://wordpress.stackexchange.com/users/102593",
"pm_score": 1,
"selected": false,
"text": "<p>You can install a new wordpress in a sub folder, let's call it \"www2\", so you'll have this URL : </p>\n\n<pr... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260105",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73939/"
] | This is a question I can't find the answer to:
**Can I run two separate Multisite networks under one domain?**
Here's the scenario, to better explain, we have a company website that already uses a WordPress Multisite network to run our country sites, like so:
```
http://www.companysite.com/
http://www.companysite.com/fr/
http://www.companysite.com/se/
http://www.companysite.com/de/
http://www.companysite.com/jp/
http://www.companysite.com/cn/
etc.
```
All of these sites use the same theme, the same plugins, so it makes sense to run them off one network.
Then we have a bunch of separate "stand-alone" wordpress sites that are marketing "campaign"-based sites, each one unique, usually developed by 3rd parties, with their own themes and plugins, which run of sub-directories of the multisite installations:
```
http://www.companysite.com/education
http://www.companysite.com/marketing
http://www.companysite.com/innovation
etc.
```
We don't really want to run them off the same Multisite installation because these use different themes and plugins, are written by 3rd parties, are subject to spikes due to marketing campaigns, and are less secure/stable than our country based sites network.
However, we do need them to be on the same domain...
Which brings me back to my original question:
**Can I run two separate Multisite networks under one domain?**
Thanks for reading! | You can not run different networks or different Multisite installations under one domain in the default possibilities of WP. But you can use one Multiste with multiple networks with the help of a plugin - <https://wordpress.org/plugins/wp-multi-network/>
With this plugin get you the chance to create different networks with sites in one installation, one Multisite. Like the follow structure example.
```
http://www.companysite.com/education
-- /www.companysite.com/education/de
-- /www.companysite.com/education/en
-- ...
http://www.companysite.com/marketing
-- /www.companysite.com/marketing/de
-- /www.companysite.com/marketing/en
-- ...
http://www.companysite.com/innovation
-- /www.companysite.com/innovation/de
-- /www.companysite.com/innovation/en
-- ...
``` |
260,114 | <p>i'm working on a plugin and i got a checkbox with the setting code:</p>
<pre><code> register_setting('plugin551-setting-group', 'livechat_option');
</code></pre>
<p>I want it to be default true, the checkbox in the setting page is now default false.
How can i do this?</p>
| [
{
"answer_id": 260109,
"author": "Sami",
"author_id": 102593,
"author_profile": "https://wordpress.stackexchange.com/users/102593",
"pm_score": 1,
"selected": false,
"text": "<p>You can install a new wordpress in a sub folder, let's call it \"www2\", so you'll have this URL : </p>\n\n<pr... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115020/"
] | i'm working on a plugin and i got a checkbox with the setting code:
```
register_setting('plugin551-setting-group', 'livechat_option');
```
I want it to be default true, the checkbox in the setting page is now default false.
How can i do this? | You can not run different networks or different Multisite installations under one domain in the default possibilities of WP. But you can use one Multiste with multiple networks with the help of a plugin - <https://wordpress.org/plugins/wp-multi-network/>
With this plugin get you the chance to create different networks with sites in one installation, one Multisite. Like the follow structure example.
```
http://www.companysite.com/education
-- /www.companysite.com/education/de
-- /www.companysite.com/education/en
-- ...
http://www.companysite.com/marketing
-- /www.companysite.com/marketing/de
-- /www.companysite.com/marketing/en
-- ...
http://www.companysite.com/innovation
-- /www.companysite.com/innovation/de
-- /www.companysite.com/innovation/en
-- ...
``` |
260,117 | <p>I am new to wordpress, I am trying to develop a theme on localhost, I am trying to load style.css using this code in functions.php</p>
<pre><code>function add_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
</code></pre>
<p>And style.css is</p>
<pre><code>body{background:green;}
</code></pre>
<p>But this code is not working </p>
<p>Can someone explain what i am doing wrong here ?</p>
| [
{
"answer_id": 260118,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": 4,
"selected": true,
"text": "<p>Are you sure you theme is active?</p>\n\n<p>If you see your style.css code it should not have only the CSS code ... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114573/"
] | I am new to wordpress, I am trying to develop a theme on localhost, I am trying to load style.css using this code in functions.php
```
function add_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
```
And style.css is
```
body{background:green;}
```
But this code is not working
Can someone explain what i am doing wrong here ? | Are you sure you theme is active?
If you see your style.css code it should not have only the CSS code but also the Theme defination at header of your style.css.
Please make sure if your theme is active.
The above code for loading CSS file looks good and should work if your theme is active.
**Update** :
Have you added `wp_head()` and `wp_footer()` in `header.php` and `footer.php` respectively?
`wp_head()` should be added before `</head>` tag in your HTML and `wp_footer()` should be added before `</body>` tag in HTML. |
260,134 | <p>I am getting post id from url like this</p>
<pre><code>https://www.example.com/download/?id=241
</code></pre>
<p>and in base of this id i want to get post data from db but it is getting nothing i tried this code</p>
<pre><code> <?php
$id = $_GET['id'];
// WP_Query arguments
$args = array (
'category_name' => 'download',
'showposts' => '1',
'post_id' => $id,
'post_type' => 'page'
);
// The Query
$my_query = new WP_Query( $args );
//print_r($my_query);
if ($my_query->have_posts() ) : while ($my_query->have_posts() ) : $my_query->the_post(); // Start the loop
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id, true);
?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" target="_blank">
<img src="<?php echo $thumb_url[0]; ?>" />
<h3><?php the_title(); ?></h3>
<time>تاريخ النشر: <?php the_time('l, F j, Y'); ?></time>
</a>
<?php
endwhile; endif;// End the Loop and Check for Posts
wp_reset_query(); // Reset the loop
?>
</code></pre>
<p>So i want to get the data by using the <code>id</code> i am getting through url. So please tell me what can i do with my code</p>
| [
{
"answer_id": 260135,
"author": "ehsan",
"author_id": 109403,
"author_profile": "https://wordpress.stackexchange.com/users/109403",
"pm_score": 1,
"selected": false,
"text": "<p>You may use $_GET parameter to get the id.</p>\n\n<pre><code>$id = $_GET['id'];\n</code></pre>\n\n<p>Or try t... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113134/"
] | I am getting post id from url like this
```
https://www.example.com/download/?id=241
```
and in base of this id i want to get post data from db but it is getting nothing i tried this code
```
<?php
$id = $_GET['id'];
// WP_Query arguments
$args = array (
'category_name' => 'download',
'showposts' => '1',
'post_id' => $id,
'post_type' => 'page'
);
// The Query
$my_query = new WP_Query( $args );
//print_r($my_query);
if ($my_query->have_posts() ) : while ($my_query->have_posts() ) : $my_query->the_post(); // Start the loop
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id, true);
?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" target="_blank">
<img src="<?php echo $thumb_url[0]; ?>" />
<h3><?php the_title(); ?></h3>
<time>تاريخ النشر: <?php the_time('l, F j, Y'); ?></time>
</a>
<?php
endwhile; endif;// End the Loop and Check for Posts
wp_reset_query(); // Reset the loop
?>
```
So i want to get the data by using the `id` i am getting through url. So please tell me what can i do with my code | You may use $\_GET parameter to get the id.
```
$id = $_GET['id'];
```
Or try this:
```
global $post;
echo $post->ID;
```
But it seems you have a problem in the args array. when you know the exact id of requested post you don't need to use it like that. you can use this instead:
```
get_post($id);
```
And then you do not need to loop through because you have one post to show. |
260,141 | <p>i'm try to filter posts by an cascade dropdown categories.
But when i select an option of the cascade, he showing all the posts.
How can i filter ONLY posts through the selected option?</p>
<p>This is my structure:</p>
<p><strong>Functions.php</strong></p>
<pre><code> function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', get_template_directory_uri() . '/assets/js/ajax-filter-posts.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'exclude' => '1,2,4,5,7,8,9,10,11,12',
'post_type' => 'post',
'nopaging' => true, // show all posts in one go
);
echo $taxonomy;
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="col-md-4">
<div class="img-thumb">
<a href="<?php the_field('link_do_case'); ?>">
<?php the_post_thumbnail(); ?>
</a>
</div>
<small><?php the_title(); ?></small>
</div>
<?php endwhile; ?>
<?php else: ?>
<h2>Case não encontrado</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
</code></pre>
<p>This is my script</p>
<pre><code>jQuery(document).ready(function(jQuery) {
jQuery('.post-tags select').on('change', function(event) {
console.log('mudou');
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = jQuery(this).attr('title');
// After user click on tag, fade out list of posts
jQuery('.tagged-posts').fadeOut();
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
taxonomy: selecetd_taxonomy, // selected tag
};
jQuery.post( afp_vars.afp_ajax_url, data, function(response) {
if( response ) {
// Display posts on page
jQuery('.tagged-posts').html( response );
// Restore div visibility
jQuery('.tagged-posts').fadeIn();
};
});
});
});
</code></pre>
<p>And this is my structure page</p>
<pre><code><div id="ajax-cases">
<?php
// WP Query
$args = array(
'post_type' => 'post',
'exclude' => '1,2,4,5,7,8,9,10,11',
'post_status' => 'publish',
'nopaging' => true, // show all posts in one go
);
$query = new WP_Query( $args );
$tax = 'category';
$terms = get_terms( $tax, $args);
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<h2>Busque pelo tipo de Trabalho</h2>
<?php
echo '<select>';
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '<option value="' . $term_link . '" class="tax-filter">' . $term->name . '</option> ';
}
echo '</select>';
?>
</div>
<?php endif ;?>
<div class="tagged-posts">
// here must be show the posts selected trough the category option
</div>
</code></pre>
<p></p>
| [
{
"answer_id": 260135,
"author": "ehsan",
"author_id": 109403,
"author_profile": "https://wordpress.stackexchange.com/users/109403",
"pm_score": 1,
"selected": false,
"text": "<p>You may use $_GET parameter to get the id.</p>\n\n<pre><code>$id = $_GET['id'];\n</code></pre>\n\n<p>Or try t... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84579/"
] | i'm try to filter posts by an cascade dropdown categories.
But when i select an option of the cascade, he showing all the posts.
How can i filter ONLY posts through the selected option?
This is my structure:
**Functions.php**
```
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', get_template_directory_uri() . '/assets/js/ajax-filter-posts.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'exclude' => '1,2,4,5,7,8,9,10,11,12',
'post_type' => 'post',
'nopaging' => true, // show all posts in one go
);
echo $taxonomy;
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="col-md-4">
<div class="img-thumb">
<a href="<?php the_field('link_do_case'); ?>">
<?php the_post_thumbnail(); ?>
</a>
</div>
<small><?php the_title(); ?></small>
</div>
<?php endwhile; ?>
<?php else: ?>
<h2>Case não encontrado</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
```
This is my script
```
jQuery(document).ready(function(jQuery) {
jQuery('.post-tags select').on('change', function(event) {
console.log('mudou');
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = jQuery(this).attr('title');
// After user click on tag, fade out list of posts
jQuery('.tagged-posts').fadeOut();
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
taxonomy: selecetd_taxonomy, // selected tag
};
jQuery.post( afp_vars.afp_ajax_url, data, function(response) {
if( response ) {
// Display posts on page
jQuery('.tagged-posts').html( response );
// Restore div visibility
jQuery('.tagged-posts').fadeIn();
};
});
});
});
```
And this is my structure page
```
<div id="ajax-cases">
<?php
// WP Query
$args = array(
'post_type' => 'post',
'exclude' => '1,2,4,5,7,8,9,10,11',
'post_status' => 'publish',
'nopaging' => true, // show all posts in one go
);
$query = new WP_Query( $args );
$tax = 'category';
$terms = get_terms( $tax, $args);
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<h2>Busque pelo tipo de Trabalho</h2>
<?php
echo '<select>';
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '<option value="' . $term_link . '" class="tax-filter">' . $term->name . '</option> ';
}
echo '</select>';
?>
</div>
<?php endif ;?>
<div class="tagged-posts">
// here must be show the posts selected trough the category option
</div>
``` | You may use $\_GET parameter to get the id.
```
$id = $_GET['id'];
```
Or try this:
```
global $post;
echo $post->ID;
```
But it seems you have a problem in the args array. when you know the exact id of requested post you don't need to use it like that. you can use this instead:
```
get_post($id);
```
And then you do not need to loop through because you have one post to show. |
260,180 | <p>When should you use <code>add_action</code> to enqueue or register a script, vs just using <code>wp_register_script</code> and/or <code>wp_enqueue_script</code>? In other words, both <code>example 1</code> and <code>example 2</code> below seem to accomplish the same thing when in <code>functions.php</code>, so why do so many resources say that <code>example 1</code> is the correct way of loading scripts in WP?</p>
<p><strong>Example 1:</strong></p>
<pre><code>function my_assets() {
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
}
add_action( 'wp_enqueue_scripts', 'my_assets' );
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
</code></pre>
<p>(yes, I know in example 2 you could skip registering the script and just enqueue it as necessary)</p>
| [
{
"answer_id": 260181,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 1,
"selected": false,
"text": "<p>Well it works the same <em>in the case where you tested it</em>.</p>\n\n<p>The answer could actually be some... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260180",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3811/"
] | When should you use `add_action` to enqueue or register a script, vs just using `wp_register_script` and/or `wp_enqueue_script`? In other words, both `example 1` and `example 2` below seem to accomplish the same thing when in `functions.php`, so why do so many resources say that `example 1` is the correct way of loading scripts in WP?
**Example 1:**
```
function my_assets() {
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
}
add_action( 'wp_enqueue_scripts', 'my_assets' );
```
**Example 2:**
```
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
```
(yes, I know in example 2 you could skip registering the script and just enqueue it as necessary) | Well it works the same *in the case where you tested it*.
The answer could actually be somewhat complex, but mainly having it inside an action callback only registers them when needed, just putting it inside the `functions.php` it happens always when the theme is active.
First of all this can be a waste of performance, registering stuff that is never used. You might think that it should be there in any case, but actually in WP there are plenty of situations where frontend JS/CSS is totally irrelevant. The most obvious situation is the backend. But also some plugin might create an endpoint that doesn't need JS/CSS. And there are plenty more of that.
Last but not least by having this on an action third party code (plugins, child themes) can unhook the callback to e.g. replace it with something else.
I hope this gives you a basic understanding why it is good practice to only do stuff on the appropriate hook.
To close things this could also be relevant/interesting for you: <https://wordpress.stackexchange.com/a/21579/47733> |
260,199 | <p>Im using the following to access tables information from my Wordpress DB</p>
<pre><code> require_once(ABSPATH . 'wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($conn, DB_NAME);
</code></pre>
<p>It works fine I'm able to connect and display the information. The trouble is when I try to do the same thing from a plugin within the Dashboard under tools, I get the following message:</p>
<blockquote>
<p>Notice: Use of undefined constant ABSPATH - assumed 'ABSPATH' in
C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
on line 2</p>
<p>Warning: require_once(ABSPATHwp-config.php): failed to open stream: No
such file or directory in
C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
on line 2</p>
<p>Fatal error: require_once(): Failed opening required
'ABSPATHwp-config.php' (include_path='.;C:\xampp\php\PEAR') in
C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
on line 2</p>
</blockquote>
<p>I have checked my wp config and I do have the following</p>
<pre><code> /** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
</code></pre>
<p>Is there something I am missing with my implementation?</p>
<p>Thanks</p>
| [
{
"answer_id": 260241,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": -1,
"selected": false,
"text": "<p>You are probably just missing the slash in the <code>require_once</code>. Change it to:</p>\n\n<pre><cod... | 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260199",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115478/"
] | Im using the following to access tables information from my Wordpress DB
```
require_once(ABSPATH . 'wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($conn, DB_NAME);
```
It works fine I'm able to connect and display the information. The trouble is when I try to do the same thing from a plugin within the Dashboard under tools, I get the following message:
>
> Notice: Use of undefined constant ABSPATH - assumed 'ABSPATH' in
> C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
> on line 2
>
>
> Warning: require\_once(ABSPATHwp-config.php): failed to open stream: No
> such file or directory in
> C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
> on line 2
>
>
> Fatal error: require\_once(): Failed opening required
> 'ABSPATHwp-config.php' (include\_path='.;C:\xampp\php\PEAR') in
> C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
> on line 2
>
>
>
I have checked my wp config and I do have the following
```
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
```
Is there something I am missing with my implementation?
Thanks | I'm guessing this is a custom "plugin" where you are wanting to run a file externally that connects to the WordPress database, not really as a standard plugin which loads within WordPress environment, as in that case as @belinus says you can just use `$wpdb` class.
Anyway, since `ABSPATH` is defined IN `wp-config.php`, you can't use `ABSPATH` to find and load `wp-config.php` - because it hasn't loaded and thus isn't defined yet. That's the flawed logic... hence the errors you are getting.
If you know for certain that `wp-config.php` is in a directory above where the "plugin" file is, you can do something like this:
```
function find_require($file,$folder=null) {
if ($folder === null) {$folder = dirname(__FILE__);}
$path = $folder.'/'.$file;
if (file_exists($path)) {require($path); return $folder;}
else {
$upfolder = find_require($file,dirname($folder));
if ($upfolder != '') {return $upfolder;}
}
}
$configpath = find_require('wp-config.php');
```
This will recursively search for `wp-config.php` above the plugin file directory and load it when it does. (Again this assumes the `wp-config.php` is located in a directory above the plugin file.) |
260,227 | <p>So I have this theme where there is an about section that is showing in the customizer, but there isn't a specific post type on the admin page that adds post to this section.</p>
<p>How do I add post to the about section with the template code stated below.</p>
<pre><code>if(isset($xt_corporate_lite_opt['xt_about_page']) &&
$xt_corporate_lite_opt['xt_about_page'] != '') {
$xt_query = new WP_Query(array(
'page_id' => $xt_corporate_lite_opt['xt_about_page']
));
if ($xt_query->have_posts()) {
while ($xt_query->have_posts()) {
$xt_query->the_post();
the_content();
}
}
wp_reset_postdata();
}
</code></pre>
| [
{
"answer_id": 260243,
"author": "1naveengiri",
"author_id": 114894,
"author_profile": "https://wordpress.stackexchange.com/users/114894",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this code to show only post.</p>\n\n<pre><code>if(isset($xt_corporate_lite_opt['xt_about_pa... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260227",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115499/"
] | So I have this theme where there is an about section that is showing in the customizer, but there isn't a specific post type on the admin page that adds post to this section.
How do I add post to the about section with the template code stated below.
```
if(isset($xt_corporate_lite_opt['xt_about_page']) &&
$xt_corporate_lite_opt['xt_about_page'] != '') {
$xt_query = new WP_Query(array(
'page_id' => $xt_corporate_lite_opt['xt_about_page']
));
if ($xt_query->have_posts()) {
while ($xt_query->have_posts()) {
$xt_query->the_post();
the_content();
}
}
wp_reset_postdata();
}
``` | You can try this code to show only post.
```
if(isset($xt_corporate_lite_opt['xt_about_page']) && $xt_corporate_lite_opt['xt_about_page'] != '') {
$args = array( 'post_type' => 'post');
$xt_query = new WP_Query($args);
if ($xt_query->have_posts()) {
while ($xt_query->have_posts()) {
$xt_query->the_post();
the_content();
}
}
wp_reset_postdata();
}
```
if you have any doubt in WP\_Query.
then you could check this link in detail.
<https://codex.wordpress.org/Class_Reference/WP_Query> |
260,236 | <p>Is there any way that I can log anything in WordPress similar to logs we can do it in Magento?</p>
<p>I am integrating a custom plugin in that I have added few functions with help of hooks, So I need to debug something in it. In this I need if I can enter any text or data into WordPress logs.</p>
<p>If so Please let me know the procedure for generating log into WordPress.</p>
| [
{
"answer_id": 260246,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress can do logging! Check out the WordPress debugging page here <a href=\"https://codex.wordpress.org/Debug... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260236",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60922/"
] | Is there any way that I can log anything in WordPress similar to logs we can do it in Magento?
I am integrating a custom plugin in that I have added few functions with help of hooks, So I need to debug something in it. In this I need if I can enter any text or data into WordPress logs.
If so Please let me know the procedure for generating log into WordPress. | You can enable WordPress logging adding this to `wp-config.php`:
```
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
```
you can write to the log file using the [`error_log()` function](https://www.php.net/manual/en/function.error-log.php) provided by PHP.
The following code snippet is a very useful function wrapper for it, make it available in your plugin:
```
if (!function_exists('write_log')) {
function write_log($log) {
if (true === WP_DEBUG) {
if (is_array($log) || is_object($log)) {
error_log(print_r($log, true));
} else {
error_log($log);
}
}
}
}
write_log('THIS IS THE START OF MY CUSTOM DEBUG');
//i can log data like objects
write_log($whatever_you_want_to_log);
```
if you cant find the `debug.log` file, try generating something for it, since it will not be created if there are no `errors`, also in some hosted servers you might need to check where the error log is located using php info. |
260,249 | <p>I'm trying to write a plugin that adds a value from a meta box to a post on save_post. But I can't figure out how to get the value from the form field in the meta box This is the relevant code:</p>
<pre><code>function sw_add_document_meta_boxes() {
if (get_current_screen()->id == 'dokument') {
add_meta_box('access_level', 'Tilgangsnivå', 'sw_ac_meta_box');
}
}
function sw_ac_meta_box() {
$html = '<p class="description">';
$html .= 'Velg laveste tilgangsnivå';
$html .= '</p>';
$html .= '<select name="access_level" id="access_level">';
$html .= '<option value="4">Ansatt</option>';
$html .= '<option value="3">Fagansvarlig</option>';
$html .= '<option value="2">Daglig leder</option>';
$html .= '<option value="1">Superbruker</option>';
$html .= '</select>';
echo $html;
}
function sw_ac_set_access_level($id) {
$meta_value =
add_post_meta($id, 'access_level', $meta_value, true);
}
add_action('add_meta_boxes', 'sw_add_document_meta_boxes');
add_action('save_post', 'sw_ac_set_access_level');
</code></pre>
<p>I guess my question is, what should I write on the line '$meta_value =' in the 'sw_ac_set_access_level()' function? Take into account that I'm a total wordpress noob, so I might be on the wrong track entirely.</p>
| [
{
"answer_id": 260246,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress can do logging! Check out the WordPress debugging page here <a href=\"https://codex.wordpress.org/Debug... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115521/"
] | I'm trying to write a plugin that adds a value from a meta box to a post on save\_post. But I can't figure out how to get the value from the form field in the meta box This is the relevant code:
```
function sw_add_document_meta_boxes() {
if (get_current_screen()->id == 'dokument') {
add_meta_box('access_level', 'Tilgangsnivå', 'sw_ac_meta_box');
}
}
function sw_ac_meta_box() {
$html = '<p class="description">';
$html .= 'Velg laveste tilgangsnivå';
$html .= '</p>';
$html .= '<select name="access_level" id="access_level">';
$html .= '<option value="4">Ansatt</option>';
$html .= '<option value="3">Fagansvarlig</option>';
$html .= '<option value="2">Daglig leder</option>';
$html .= '<option value="1">Superbruker</option>';
$html .= '</select>';
echo $html;
}
function sw_ac_set_access_level($id) {
$meta_value =
add_post_meta($id, 'access_level', $meta_value, true);
}
add_action('add_meta_boxes', 'sw_add_document_meta_boxes');
add_action('save_post', 'sw_ac_set_access_level');
```
I guess my question is, what should I write on the line '$meta\_value =' in the 'sw\_ac\_set\_access\_level()' function? Take into account that I'm a total wordpress noob, so I might be on the wrong track entirely. | You can enable WordPress logging adding this to `wp-config.php`:
```
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
```
you can write to the log file using the [`error_log()` function](https://www.php.net/manual/en/function.error-log.php) provided by PHP.
The following code snippet is a very useful function wrapper for it, make it available in your plugin:
```
if (!function_exists('write_log')) {
function write_log($log) {
if (true === WP_DEBUG) {
if (is_array($log) || is_object($log)) {
error_log(print_r($log, true));
} else {
error_log($log);
}
}
}
}
write_log('THIS IS THE START OF MY CUSTOM DEBUG');
//i can log data like objects
write_log($whatever_you_want_to_log);
```
if you cant find the `debug.log` file, try generating something for it, since it will not be created if there are no `errors`, also in some hosted servers you might need to check where the error log is located using php info. |
260,284 | <p>My Server Env for a wordpress site is as follows:</p>
<pre><code>---------- --------- -------------
| Client | <-- HTTPS --> | Proxy | <-- HTTP --> | Wordpress |
---------- --------- -------------
</code></pre>
<p>The Problem is that the Wordpress Site itself is served internally over HTTP but the Client communicates over HTTPS with the Proxy. Since Wordpress is configured with HTTP it returns links and images-src with "http://" which leads to <code>mixed-content</code> errors in the browsers. (Eg. all css / script links generated by wp_head() return http:// urls)</p>
<p>Can i configure Wordpress to generate only "https://" urls, even if it's serverd over HTTP?</p>
<p>Wordpress runs on nginx webserver<br>
The Proxy is also nginx </p>
| [
{
"answer_id": 260293,
"author": "hcheung",
"author_id": 111577,
"author_profile": "https://wordpress.stackexchange.com/users/111577",
"pm_score": 3,
"selected": true,
"text": "<p>Please take a look at <a href=\"https://wordpress.org/support/article/administration-over-ssl/\" rel=\"nofol... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86177/"
] | My Server Env for a wordpress site is as follows:
```
---------- --------- -------------
| Client | <-- HTTPS --> | Proxy | <-- HTTP --> | Wordpress |
---------- --------- -------------
```
The Problem is that the Wordpress Site itself is served internally over HTTP but the Client communicates over HTTPS with the Proxy. Since Wordpress is configured with HTTP it returns links and images-src with "http://" which leads to `mixed-content` errors in the browsers. (Eg. all css / script links generated by wp\_head() return http:// urls)
Can i configure Wordpress to generate only "https://" urls, even if it's serverd over HTTP?
Wordpress runs on nginx webserver
The Proxy is also nginx | Please take a look at [Administation Over SSL](https://wordpress.org/support/article/administration-over-ssl/), particularly the "Using a Reverse Proxy" section. |
260,311 | <p>I'm new to Wordpress theme development. I'd like to make a simple Testimonial page that a non-technical user can add more testimonial later. Here's the example of the page:
<a href="http://heartyjuice.com.au/testimonials/" rel="nofollow noreferrer">Testimonials page</a></p>
<p>I'd like to have a admin screen where user input the name, upload the picture, and the testimonial detail. After that the testimonial item can be add to the page.</p>
<p>Please show me how to approach this. What is the right direction to go about this?</p>
| [
{
"answer_id": 260316,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 2,
"selected": true,
"text": "<p>I would suggest a custom post type for your Testimonials. Each will be created as an individual post and you ... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260311",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115555/"
] | I'm new to Wordpress theme development. I'd like to make a simple Testimonial page that a non-technical user can add more testimonial later. Here's the example of the page:
[Testimonials page](http://heartyjuice.com.au/testimonials/)
I'd like to have a admin screen where user input the name, upload the picture, and the testimonial detail. After that the testimonial item can be add to the page.
Please show me how to approach this. What is the right direction to go about this? | I would suggest a custom post type for your Testimonials. Each will be created as an individual post and you will have the ability to query, sort, categorize, your testimonials just as you can with blog posts, or any other post type. Non-technical site admins can simply "add new testimonial" and edit existing, etc, just as if they were working with pages, blog posts, etc
You must register your `testimonial` post type for that to happen. An extremely simple example. You will want to define many more of the optional parameters than this example:
```
function wpse_register_post_types() {
$args = array(
'public' => true,
'label' => 'Testimonials'
);
register_post_type( 'testimonial', $args );
}
add_action( 'init', 'wpse_register_post_types' );
```
Full WP Codex documentation here:
<https://codex.wordpress.org/Function_Reference/register_post_type>
This is an extremely simplified example to show the basics: create a function to handle registration, hook that function to WP's `init` action.
In a real application you will want to define your labels and other arguments for the `register_post_type()` function.
Depending on how you intend to use the testimonials on the front end, you will need templates for your new custom post type:
`archive-testimonial.php` <-- this will display all of the published testimonials; your example page
`single-testimonial.php` <-- used to display a single testimonial; when a user clicks through to see all of the details on a single testimonial
This will get you started. For advanced features, like displaying random testimonials on a page, you'll want to read up on using the `WP_Query` class for custom queries.
Welcome to WPSE! |
260,315 | <p>I am trying to clean up a DB of 4000+ posts and the editors TAGGED the posts that they want to keep with an "audit2017" tag. Is there a way with SQL to select all posts *without this tag and delete them?</p>
<p>I am not very experienced with SQL but can manage this if I had the right query.</p>
<p>Any help appreciated, thanks!</p>
| [
{
"answer_id": 260383,
"author": "Mihai Apetrei",
"author_id": 115589,
"author_profile": "https://wordpress.stackexchange.com/users/115589",
"pm_score": 0,
"selected": false,
"text": "<p>Was looking into this to help you come with a solution. I'm not able to find one for the sql panel, b... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115559/"
] | I am trying to clean up a DB of 4000+ posts and the editors TAGGED the posts that they want to keep with an "audit2017" tag. Is there a way with SQL to select all posts \*without this tag and delete them?
I am not very experienced with SQL but can manage this if I had the right query.
Any help appreciated, thanks! | I just created a function that can bulk delete posts that doesn't have specific tag(s).
You need to have the IDs of the tags that you want to keep their posts.
[In case you don't know how to get those IDs: Quick solution is go to tags page on the website admin panel. Click on the tag. In the new page address bar you can see the tag\_id]
Replace the "TagID"s with your actual tag IDs on this line:
```
$tags_to_delete = array( $TagID1, $TagID2 , ... );
```
Then place the code at the end of your theme's functions.php file. Open your homepage. It will move all the posts that don't have specific tag(s) to trash.
This code will be run every time that you open a page in your frontend.
The runtime depends on you number of post and your server configuration.
I tested it for about 3500 posts on a not very high config server and it took about 40 seconds to finish.
I strongly suggest to remove the code from your website after you are done with it.
```
// Change the $TagIDs with the tag IDs in your database
$tags_to_delete = array( $TagID1, $TagID2 , ... );
// This function will bulk delete posts that don't have specific tag(s)
function delete_posts_by_not_tag( $tags ) {
// WP_Query arguments
$args = array(
'post_type' => array( 'post' ),
'nopaging' => true,
'posts_per_page' => '-1',
'tag__not_in' => array( $tags ),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
$totalpost = $query->found_posts;
echo "Number of Posts: " . $totalpost;
echo "<hr>";
while ( $query->have_posts() ) {
$query->the_post();
$current_id = $post->ID;
wp_delete_post( $current_id );
echo "Post by ID '" . $current_id . "' is deleted.<br>";
}
echo "<hr>";
} else {
echo "No post found to delete!";
}
// Restore original Post Data
wp_reset_postdata();
}
// Run the function to delete all the posts that don't have specific tag(s)
delete_posts_by_not_tag( $tags_to_delete );
``` |
260,359 | <p>I'm having a heck of a time with this! I'm trying to force this page to only show a limited amount of words regardless if they insert a readmore tag.</p>
<p>I was going to use the_excerpt, but it doesn't add a readmore link at the end of the excerpt.</p>
<p>I have my index page pulling my blog roll by using this code:</p>
<pre><code><div class="entry-content">
<?php
/* translators: %s: Name of current post */
the_content( sprintf(
__( 'more %s <span class="meta-nav">...</span>', 'gateway' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
) );
?>
</div>
</code></pre>
<p>In my reading settings I have set "For each article in a feed, show" to "summary".</p>
<p>So I guess my question is this: Is there a away to limit the_content() or alternatively add a read more to the_excerpt()?</p>
| [
{
"answer_id": 260361,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": false,
"text": "<p>Try <code>wp_trim_words()</code> <a href=\"https://codex.wordpress.org/Function_Reference/wp_trim_words\" rel=\"n... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260359",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77767/"
] | I'm having a heck of a time with this! I'm trying to force this page to only show a limited amount of words regardless if they insert a readmore tag.
I was going to use the\_excerpt, but it doesn't add a readmore link at the end of the excerpt.
I have my index page pulling my blog roll by using this code:
```
<div class="entry-content">
<?php
/* translators: %s: Name of current post */
the_content( sprintf(
__( 'more %s <span class="meta-nav">...</span>', 'gateway' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
) );
?>
</div>
```
In my reading settings I have set "For each article in a feed, show" to "summary".
So I guess my question is this: Is there a away to limit the\_content() or alternatively add a read more to the\_excerpt()? | I couldn't get this resolved with the\_content() so i went simple and this works:
```
the_excerpt();
echo '<a href="' . esc_url( get_the_permalink() ) . '"> more...</a>';
``` |
260,371 | <p>I have made a child theme of a themify theme. I used thier example on enqueuing as well as my own. In both cases the child css is loaded after the parent. </p>
<p>Loaded on Line <code>53</code></p>
<pre><code><link rel='stylesheet' id='parent-style-css' href='https://example.com/wp-content/themes/themify-ultra/style.css?ver=4.7.3' type='text/css' media='all' />
</code></pre>
<p>Loaded on Line <code>69</code></p>
<pre><code><link rel='stylesheet' id='theme-style-css' href='https://example.com/wp-content/themes/Ultra-Child/style.css?ver=1.0.0' type='text/css' media='all' />
</code></pre>
<p>However the elements in the line 53 file override the 69 file. I have tried a few things that have changed positions and one that even loads the same child stylesheet twice. The earlier stylesheet caches and overrides unless I change the version number. It still overrides but will update if I change the version. Exact same elements in both files, one change, no <code>!important</code>. Why is the first one overriding the second?</p>
<p>This is the entire Child functions.php:</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', PHP_INT_MAX);
function theme_enqueue_styles() {
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css' );
}
// Queue parent style followed by child/customized style
add_action( 'wp_enqueue_scripts', 'theme_enqueue_parent_styles', 9);
function theme_enqueue_parent_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
</code></pre>
| [
{
"answer_id": 260390,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>I looked at my child theme's functions.php and I found that I had commented out the line to enqueue the child s... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260371",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70863/"
] | I have made a child theme of a themify theme. I used thier example on enqueuing as well as my own. In both cases the child css is loaded after the parent.
Loaded on Line `53`
```
<link rel='stylesheet' id='parent-style-css' href='https://example.com/wp-content/themes/themify-ultra/style.css?ver=4.7.3' type='text/css' media='all' />
```
Loaded on Line `69`
```
<link rel='stylesheet' id='theme-style-css' href='https://example.com/wp-content/themes/Ultra-Child/style.css?ver=1.0.0' type='text/css' media='all' />
```
However the elements in the line 53 file override the 69 file. I have tried a few things that have changed positions and one that even loads the same child stylesheet twice. The earlier stylesheet caches and overrides unless I change the version number. It still overrides but will update if I change the version. Exact same elements in both files, one change, no `!important`. Why is the first one overriding the second?
This is the entire Child functions.php:
```
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', PHP_INT_MAX);
function theme_enqueue_styles() {
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css' );
}
// Queue parent style followed by child/customized style
add_action( 'wp_enqueue_scripts', 'theme_enqueue_parent_styles', 9);
function theme_enqueue_parent_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
``` | Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS.
Chromes console still showed it as the remote CSS file even though it was inlined.
Disabling the built in minification fixed the issue. |
260,373 | <p>I'm using twentyseventeen theme as base to design my own, but when i use wp_nav_menu to print menus, it adds some unwanted svg elements which break my design. Elements are like:</p>
<pre><code><svg class="icon icon-angle-down" aria-hidden="true" role="img">
<use href="#icon-angle-down" xlink:href="#icon-angle-down"></use> </svg>
</code></pre>
<p>How can i disable this?</p>
| [
{
"answer_id": 260390,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>I looked at my child theme's functions.php and I found that I had commented out the line to enqueue the child s... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260373",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115587/"
] | I'm using twentyseventeen theme as base to design my own, but when i use wp\_nav\_menu to print menus, it adds some unwanted svg elements which break my design. Elements are like:
```
<svg class="icon icon-angle-down" aria-hidden="true" role="img">
<use href="#icon-angle-down" xlink:href="#icon-angle-down"></use> </svg>
```
How can i disable this? | Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS.
Chromes console still showed it as the remote CSS file even though it was inlined.
Disabling the built in minification fixed the issue. |
260,375 | <p>Im working with custom post types - named 'Products'</p>
<p>I have multiple taxonomies registered - 'Category' and 'Dosage'</p>
<p>And I'm trying to setup pages that only display custom post types 'products' IF taxonomy Category='injectors' AND Dosage='1ml, 2ml, 5ml' </p>
<p>I hope that makes sense - manage to get custom post archives working fine for a single taxonomy, but not sure about filtering by multiple.</p>
<p>Cheers,</p>
<p>This is the code i'm trying to get work but it doesn't</p>
<pre><code><?php
$myquery['tax_query'] = array(
'relation' => 'OR',
array(
'taxonomy' => 'product_category',
'terms' => array('shrouded'),
'field' => 'slug',
),
array(
'taxonomy' => 'dosages',
'terms' => array( '1ml' ),
'field' => 'slug',
),
);
query_posts($myquery); ?>
</code></pre>
| [
{
"answer_id": 260390,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>I looked at my child theme's functions.php and I found that I had commented out the line to enqueue the child s... | 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260375",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115588/"
] | Im working with custom post types - named 'Products'
I have multiple taxonomies registered - 'Category' and 'Dosage'
And I'm trying to setup pages that only display custom post types 'products' IF taxonomy Category='injectors' AND Dosage='1ml, 2ml, 5ml'
I hope that makes sense - manage to get custom post archives working fine for a single taxonomy, but not sure about filtering by multiple.
Cheers,
This is the code i'm trying to get work but it doesn't
```
<?php
$myquery['tax_query'] = array(
'relation' => 'OR',
array(
'taxonomy' => 'product_category',
'terms' => array('shrouded'),
'field' => 'slug',
),
array(
'taxonomy' => 'dosages',
'terms' => array( '1ml' ),
'field' => 'slug',
),
);
query_posts($myquery); ?>
``` | Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS.
Chromes console still showed it as the remote CSS file even though it was inlined.
Disabling the built in minification fixed the issue. |
260,399 | <p>I´m building a child theme for a parent theme that loads in its functions.php <strong>all</strong> its scripts in a single minified JS file. And it does so before the closing body tag by setting the last parameter of <code>wp_enqueue_script()</code> to "true"</p>
<p>However, note that this <strong>single file</strong> includes several libraries before the developer´s code shows up at the very bottom. So, by scrolling down the file, you´d get: jQuery, Parsley, Slick, Select2 and, finally, developer´s code. </p>
<p>Like I said, <strong>all in the same file</strong>, one after the other, resulting in a BIG file (242kb minified, over 20K lines of code).</p>
<p>So, when creating my custom jQuery scripts in my child theme, I´m able to load them on the page, but none of my scripts work. Console shows "Uncaught ReferenceError: $ is not defined" which, I assume, indicates that jQuery is not installed... </p>
<p>But jQuery IS in that single minified file I mentioned before. And my theme uses jQuery... So I´m puzzled. Why is it not working?</p>
<p>I suspect this has something to do with this approach made by the parent theme´s developer, where he did not install jQuery like you normally would. Overriding the original file by copying it entirely only to include a few simple lines seems not the way to go... any thoughts on how to solve this?</p>
<p>I´m loading my script in my child theme´s function.php like this:</p>
<pre><code>define( 'BLK_BOX_VERSION', '1.0.0' );
define( 'BLK_BOX_TEMPLATE_URI', get_stylesheet_directory_uri() );
define( 'BLK_BOX_THEME_SLUG', 'black-box' );
if ( ! function_exists( 'headerNavBar_script' ) ) :
function headerNavBar_script() {
wp_enqueue_script( BLK_BOX_THEME_SLUG . '-scripts', BLK_BOX_TEMPLATE_URI . '/static/dist/scripts/navbar-scroll.js', array(), BLK_BOX_VERSION, true );
}
endif;
add_action( 'wp_enqueue_scripts', 'headerNavBar_script' );
</code></pre>
| [
{
"answer_id": 260400,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress loads jQuery in noconflict mode. Therefore, but default, you cannot use $(). You can fix this one of ... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260399",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115596/"
] | I´m building a child theme for a parent theme that loads in its functions.php **all** its scripts in a single minified JS file. And it does so before the closing body tag by setting the last parameter of `wp_enqueue_script()` to "true"
However, note that this **single file** includes several libraries before the developer´s code shows up at the very bottom. So, by scrolling down the file, you´d get: jQuery, Parsley, Slick, Select2 and, finally, developer´s code.
Like I said, **all in the same file**, one after the other, resulting in a BIG file (242kb minified, over 20K lines of code).
So, when creating my custom jQuery scripts in my child theme, I´m able to load them on the page, but none of my scripts work. Console shows "Uncaught ReferenceError: $ is not defined" which, I assume, indicates that jQuery is not installed...
But jQuery IS in that single minified file I mentioned before. And my theme uses jQuery... So I´m puzzled. Why is it not working?
I suspect this has something to do with this approach made by the parent theme´s developer, where he did not install jQuery like you normally would. Overriding the original file by copying it entirely only to include a few simple lines seems not the way to go... any thoughts on how to solve this?
I´m loading my script in my child theme´s function.php like this:
```
define( 'BLK_BOX_VERSION', '1.0.0' );
define( 'BLK_BOX_TEMPLATE_URI', get_stylesheet_directory_uri() );
define( 'BLK_BOX_THEME_SLUG', 'black-box' );
if ( ! function_exists( 'headerNavBar_script' ) ) :
function headerNavBar_script() {
wp_enqueue_script( BLK_BOX_THEME_SLUG . '-scripts', BLK_BOX_TEMPLATE_URI . '/static/dist/scripts/navbar-scroll.js', array(), BLK_BOX_VERSION, true );
}
endif;
add_action( 'wp_enqueue_scripts', 'headerNavBar_script' );
``` | change all $ to jQuery and enque script this way so your script will load after loading jQuery and since wordpress do use prototype so we cannt use $ user jQuery
```
wp_enqueue_script('name_of_script','path',array('jquery'));
``` |
260,410 | <p>I am creating a custom admin section. I have the following code:</p>
<pre><code>// Top level menu
add_menu_page('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
// Details: https://wordpress.stackexchange.com/questions/66498/add-menu-page-with-different-name-for-first-submenu-item
add_submenu_page('Books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page');
// The Add Book menu page
add_submenu_page('Books', 'Add New Book', 'Add Book', 'publish_posts', 'add-book', 'render_add_book_page');
// The Edit Book menu page (this page is hidden from the menu, and accessed via the All Books page only)
add_submenu_page(null, 'Edit Book', 'Edit Book', 'publish_posts', 'edit-book', 'render_edit_book_page');
</code></pre>
<p>As you notice in the last line of code, the first parameter of the <code>add_submenu_page()</code> is set to <code>null</code>. This is to ensure that the <strong>Edit Book</strong> page is hidden (<a href="https://wordpress.stackexchange.com/questions/73622/add-an-admin-page-but-dont-show-it-on-the-admin-menu">more details about this here</a>). Access to the <strong>Edit Book</strong> page is done via the main menu, from the list of all books.</p>
<p>The problem is, when I go to the <strong>Edit Book</strong> page, the Admin Menu to the left collapses (on the other hand, the default WordPress behaviour is as follows: If you go to an <strong>Edit Post</strong> page, or the <strong>Edit Page</strong> page, both the <strong>Posts</strong> and <strong>Pages</strong> menu stay expanded for their respective <em>edit</em> pages). In my case, the menu collapses.</p>
<p>How can I keep the menu to the left expanded when I go to the <strong>Edit Book</strong> page, to behave in a similar fashion to that of WordPress?</p>
<p>Thanks.</p>
| [
{
"answer_id": 260415,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": false,
"text": "<p>For your particular situation, where you need to have a menu registered, but not shown unless you click on it fro... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
] | I am creating a custom admin section. I have the following code:
```
// Top level menu
add_menu_page('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
// Details: https://wordpress.stackexchange.com/questions/66498/add-menu-page-with-different-name-for-first-submenu-item
add_submenu_page('Books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page');
// The Add Book menu page
add_submenu_page('Books', 'Add New Book', 'Add Book', 'publish_posts', 'add-book', 'render_add_book_page');
// The Edit Book menu page (this page is hidden from the menu, and accessed via the All Books page only)
add_submenu_page(null, 'Edit Book', 'Edit Book', 'publish_posts', 'edit-book', 'render_edit_book_page');
```
As you notice in the last line of code, the first parameter of the `add_submenu_page()` is set to `null`. This is to ensure that the **Edit Book** page is hidden ([more details about this here](https://wordpress.stackexchange.com/questions/73622/add-an-admin-page-but-dont-show-it-on-the-admin-menu)). Access to the **Edit Book** page is done via the main menu, from the list of all books.
The problem is, when I go to the **Edit Book** page, the Admin Menu to the left collapses (on the other hand, the default WordPress behaviour is as follows: If you go to an **Edit Post** page, or the **Edit Page** page, both the **Posts** and **Pages** menu stay expanded for their respective *edit* pages). In my case, the menu collapses.
How can I keep the menu to the left expanded when I go to the **Edit Book** page, to behave in a similar fashion to that of WordPress?
Thanks. | The solution is based on the ideas provided by @Ian. Thanks.
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// The Edit Book menu page and display it as the All Books page
add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );
}
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
And we must hide the first menu item
```
add_action( 'admin_enqueue_scripts', function () {
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Load CSS file
wp_enqueue_style('book-edit', 'path/to/css/menu.css');
// Load jQuery
wp_enqueue_script('jquery');
// Load
wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');
}
});
```
And the content of `menu.css` is:
```
#toplevel_page_books li.current {
display: none;
}
#toplevel_page_books li.wp-first-item {
display: list-item;
}
```
Also the content of 'menu.js' is:
```
jQuery(document).ready(function($) {
$('#toplevel_page_books li.wp-first-item').addClass('current');
});
```
---
**TL;DR**
To understand how all this works, here is a step-by-step explanation.
**Step 1:** We add the main menu item (the *books* menu item) to display the list of books
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
}
```
**Step 2:** We add the *add-book* menu item as a submenu to the main *books* menu item
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
**Step 3:** Finishing Step 2 above adds the books menu item, The menu list on the left side would look like this:
```
Books <---------- This is the main top level menu names
Books <---------- This is the first sub-menu
Add New <---------- This is the second sub-menu
```
However, we should fix this. The intended list should look like this
```
Books <---------- This is the main top level menu names
All Books <---------- This is the first sub-menu
Add New <---------- This is the second sub-menu
```
To do this, we have to modify our code as follows:
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
**Step 4:** Next we should add a sub menu to edit books (the *edit-book* menu item). After adding his submenu, and when we are at the *edit-book* page, the menu on the left should look like this:
```
Books
All Books <---------- When we are in the 'edit-book' page, this menu item is selected and is highlighted (typically white in color), and also clicking on "All Books" would return us back to the "All Books" page.
Add New
```
The solution I tried first was what I posted in my original question, which did not work exactly. So, based on discussions with @Ian and looking at his proposed solution, I came up with this:
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
// If we are in the 'edit-book' page, then display the 'edit-book' submenu, otherwise, display the regular 'books' menu
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Display the 'edit-book' menu page and display it as the 'all-books' page
// Notice that the slug is 'edit-book', but the display name is 'All Books'
add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );
}
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
Now, if we click on the 'books' menu item, or the 'add-book' menu item, then everything is fine. However, if we try to edit an existing book then the following menu list will be displayed
```
Books
All Books <---------- This is the first sub-menu (due to the first submenu call)
All Books <---------- This is the 'edit-book' page (HIGHLIGHTED)
Add New
```
**Step 5:** Now we notice the following: By clicking on the first submenu, the "All Books" page will be rendered, and clicking on the second submenu will render the "Edit" page; and in our case, we want to render the "All Books" page.
Therefore, we have to hide the SECOND submenu and make the first submenu highlighted. This is done as follows:
```
add_action( 'admin_enqueue_scripts', function () {
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Load CSS file
wp_enqueue_style('book-edit', 'path/to/css/menu.css');
// Load jQuery
wp_enqueue_script('jquery');
// Load
wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');
}
});
```
And the content of `menu.css` is:
```
#toplevel_page_books li.current {
display: none;
}
#toplevel_page_books li.wp-first-item {
display: list-item;
}
```
Also the content of 'menu.js' is:
```
jQuery(document).ready(function($) {
$('#toplevel_page_books li.wp-first-item').addClass('current');
});
```
And now everything works like a charm. |
260,416 | <p>I'm trying to find a way to get my posts with different look depending on their category.</p>
<p>I have first tried to do it using the <a href="https://developer.wordpress.org/files/2014/10/template-hierarchy.png" rel="nofollow noreferrer">template hierarchy</a> but it seems there is no pattern for the category posts. (ie single-cat-mycategory.php)</p>
<p>So then within single.php I tried the conditional tagging using <code>is_category()</code> but my understanding it's only working for the <code>archive</code> pages.</p>
<p>Finally, I'm now trying to use the <code>is_single()</code> conditional tagging where first I'm looking for all the posts corresponding to my category and pass it as a parameter of <code>is_single()</code></p>
<p><strong>In functions.php</strong></p>
<pre><code>function get_post_id_by_cat(){
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => 'my_category',
];
$cat_query = new WP_Query( $args );
if ($cat_query -> have_posts()){
while ($cat_query -> have_posts()){
$cat_query -> the_post();
$post_ids[] = get_the_ID();
}
wp_reset_postdata();
}
</code></pre>
<p><strong>In single.php</strong></p>
<pre><code>$my_cat_posts = get_post_id_by_cat();
if (is_single($my_cat_posts)) {
while ( have_posts() ) : the_post();
//do my stuff here
endwhile;
}
</code></pre>
<p><strong>My first question</strong> is this in term of Wordpress design a good way to do this or is there a better way as my concern is mainly for performance, with this method.</p>
<p><strong>If it's ok,</strong>
My issue is that <code>$post_ids</code> is storing the data in a php object format and not an array so <code>is_single()</code> doesn't get the posts ids properly as parameter.
And i don't get how I can get it converted to an array.</p>
<p><code>$post_ids[] = to_array(get_the_ID());</code> return</p>
<blockquote>
<p>Uncaught Error: Call to undefined function to_array()</p>
</blockquote>
<p>or
<code>$post_ids[] = (array)get_the_ID();</code> return each post ids stil has object but within a array like this:</p>
<pre><code>array(8) {
[0]=>
array(1) {
[0]=>
int(5415)
}…
</code></pre>
<p>or
<code>$post_ids[] = get_object_vars(get_the_ID());</code> return </p>
<blockquote>
<p>get_object_vars() expects parameter 1 to be object, integer given</p>
</blockquote>
<p>But if pass this array it does work properly:</p>
<pre><code>$array = ['5415','5413','5411','5401'];
</code></pre>
<p>Hope this is clear enough,</p>
<p>Thanks for any input!</p>
<p>Matth.</p>
| [
{
"answer_id": 260415,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": false,
"text": "<p>For your particular situation, where you need to have a menu registered, but not shown unless you click on it fro... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110467/"
] | I'm trying to find a way to get my posts with different look depending on their category.
I have first tried to do it using the [template hierarchy](https://developer.wordpress.org/files/2014/10/template-hierarchy.png) but it seems there is no pattern for the category posts. (ie single-cat-mycategory.php)
So then within single.php I tried the conditional tagging using `is_category()` but my understanding it's only working for the `archive` pages.
Finally, I'm now trying to use the `is_single()` conditional tagging where first I'm looking for all the posts corresponding to my category and pass it as a parameter of `is_single()`
**In functions.php**
```
function get_post_id_by_cat(){
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => 'my_category',
];
$cat_query = new WP_Query( $args );
if ($cat_query -> have_posts()){
while ($cat_query -> have_posts()){
$cat_query -> the_post();
$post_ids[] = get_the_ID();
}
wp_reset_postdata();
}
```
**In single.php**
```
$my_cat_posts = get_post_id_by_cat();
if (is_single($my_cat_posts)) {
while ( have_posts() ) : the_post();
//do my stuff here
endwhile;
}
```
**My first question** is this in term of Wordpress design a good way to do this or is there a better way as my concern is mainly for performance, with this method.
**If it's ok,**
My issue is that `$post_ids` is storing the data in a php object format and not an array so `is_single()` doesn't get the posts ids properly as parameter.
And i don't get how I can get it converted to an array.
`$post_ids[] = to_array(get_the_ID());` return
>
> Uncaught Error: Call to undefined function to\_array()
>
>
>
or
`$post_ids[] = (array)get_the_ID();` return each post ids stil has object but within a array like this:
```
array(8) {
[0]=>
array(1) {
[0]=>
int(5415)
}…
```
or
`$post_ids[] = get_object_vars(get_the_ID());` return
>
> get\_object\_vars() expects parameter 1 to be object, integer given
>
>
>
But if pass this array it does work properly:
```
$array = ['5415','5413','5411','5401'];
```
Hope this is clear enough,
Thanks for any input!
Matth. | The solution is based on the ideas provided by @Ian. Thanks.
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// The Edit Book menu page and display it as the All Books page
add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );
}
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
And we must hide the first menu item
```
add_action( 'admin_enqueue_scripts', function () {
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Load CSS file
wp_enqueue_style('book-edit', 'path/to/css/menu.css');
// Load jQuery
wp_enqueue_script('jquery');
// Load
wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');
}
});
```
And the content of `menu.css` is:
```
#toplevel_page_books li.current {
display: none;
}
#toplevel_page_books li.wp-first-item {
display: list-item;
}
```
Also the content of 'menu.js' is:
```
jQuery(document).ready(function($) {
$('#toplevel_page_books li.wp-first-item').addClass('current');
});
```
---
**TL;DR**
To understand how all this works, here is a step-by-step explanation.
**Step 1:** We add the main menu item (the *books* menu item) to display the list of books
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
}
```
**Step 2:** We add the *add-book* menu item as a submenu to the main *books* menu item
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
**Step 3:** Finishing Step 2 above adds the books menu item, The menu list on the left side would look like this:
```
Books <---------- This is the main top level menu names
Books <---------- This is the first sub-menu
Add New <---------- This is the second sub-menu
```
However, we should fix this. The intended list should look like this
```
Books <---------- This is the main top level menu names
All Books <---------- This is the first sub-menu
Add New <---------- This is the second sub-menu
```
To do this, we have to modify our code as follows:
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
**Step 4:** Next we should add a sub menu to edit books (the *edit-book* menu item). After adding his submenu, and when we are at the *edit-book* page, the menu on the left should look like this:
```
Books
All Books <---------- When we are in the 'edit-book' page, this menu item is selected and is highlighted (typically white in color), and also clicking on "All Books" would return us back to the "All Books" page.
Add New
```
The solution I tried first was what I posted in my original question, which did not work exactly. So, based on discussions with @Ian and looking at his proposed solution, I came up with this:
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
// If we are in the 'edit-book' page, then display the 'edit-book' submenu, otherwise, display the regular 'books' menu
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Display the 'edit-book' menu page and display it as the 'all-books' page
// Notice that the slug is 'edit-book', but the display name is 'All Books'
add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );
}
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
Now, if we click on the 'books' menu item, or the 'add-book' menu item, then everything is fine. However, if we try to edit an existing book then the following menu list will be displayed
```
Books
All Books <---------- This is the first sub-menu (due to the first submenu call)
All Books <---------- This is the 'edit-book' page (HIGHLIGHTED)
Add New
```
**Step 5:** Now we notice the following: By clicking on the first submenu, the "All Books" page will be rendered, and clicking on the second submenu will render the "Edit" page; and in our case, we want to render the "All Books" page.
Therefore, we have to hide the SECOND submenu and make the first submenu highlighted. This is done as follows:
```
add_action( 'admin_enqueue_scripts', function () {
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Load CSS file
wp_enqueue_style('book-edit', 'path/to/css/menu.css');
// Load jQuery
wp_enqueue_script('jquery');
// Load
wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');
}
});
```
And the content of `menu.css` is:
```
#toplevel_page_books li.current {
display: none;
}
#toplevel_page_books li.wp-first-item {
display: list-item;
}
```
Also the content of 'menu.js' is:
```
jQuery(document).ready(function($) {
$('#toplevel_page_books li.wp-first-item').addClass('current');
});
```
And now everything works like a charm. |
260,427 | <p>Hi I am trying to understand when and why I should use these esc-alternatives and so far I think I understand that it is needed to secure that input is not containing wrong characters and in that causing errors/security threats.</p>
<p>What I still wonder is should I always use esc_attr in HTML fields, or example the input fields of a contact form? And should I always use esc_url for all my own urls, for example image src paths? </p>
<p>And what about the_title()?
Should I use one of these escapes to all echos in my code or only where there are possible input from users?</p>
| [
{
"answer_id": 260430,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>If the values that are in need of escaping are generate fully from your code, as it is usually in admin s... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114853/"
] | Hi I am trying to understand when and why I should use these esc-alternatives and so far I think I understand that it is needed to secure that input is not containing wrong characters and in that causing errors/security threats.
What I still wonder is should I always use esc\_attr in HTML fields, or example the input fields of a contact form? And should I always use esc\_url for all my own urls, for example image src paths?
And what about the\_title()?
Should I use one of these escapes to all echos in my code or only where there are possible input from users? | Yes! You should always be escaping
Escape Late, Escape Often
Escaping is about intent, if you intend to output a URL, use `esc_url`, and it will definately be a URL ( if the data is malicious it will be made safe )
>
> What I still wonder is should I always use esc\_attr in HTML fields, or example the input fields of a contact form? And should I always use esc\_url for all my own urls, for example image src paths?
>
>
>
If it's a hardcoded URL? E.g. `"http://example.com"` ? **No**, we know it's safe
If it's a URL from a function or some other source? E.g. `echo get_permalink()` or `echo $url`?
**Yes, you should escape** there's no way to know if it's safe
If it's a function that outputs internally and doesn't require an `echo` statement? E.g. `the_permalink()`? **No** there's no way to escape this, the function needs to escape internally. Output buffers can be used in emergencies, but that path leads to madness
>
> And what about the\_title()? Should I use one of these escapes to all echos in my code or only where there are possible input from users?
>
>
>
There's no way to escape a function that outputs internally. `the_title` should be good to use, as are the others
With 1 Exception
----------------
`bloginfo`
Avoid this function at all costs, for security reasons. `bloginfo` doesn't always escape internally, and as it outputs internally there's no way to add escaping.
### The solution
Use `get_bloginfo` and escape the result, e.g.
```
<a href="<?php echo esc_url( get_bloginfo( 'site' ) ); ?>">
```
`get_bloginfo` returns rather than outputs the value, allowing us to use escaping functions.
A Brief Note on Filters
-----------------------
Sometimes you want to pass things through a filter, such as `the_content`, but escaping the result will strip out tags.
For example, this will strip any embedded videos present:
```
echo wp_kses_post( apply_filters( 'the_content', $stuff ) );
```
The solution is instead to do this:
```
echo apply_filters( 'the_content', wp_kses_post( $stuff ) );
```
The idea being that we know the input is safe, therefore the output must be safe. This assumes that any code running on that filter also escapes accordingly. Do this for these situations with WP Core filters, but avoid needing this in your own filters and code as much as possible |
260,442 | <p>I have several post types. I want to get all custom fields associated with that post type.</p>
<p>Example:</p>
<pre><code>Post
-- image
-- Featured image
-- body
</code></pre>
<p>I need to get all fields or custom fields in array. I found a solution <a href="https://wordpress.stackexchange.com/questions/18318/how-to-display-all-custom-fields-associated-with-a-post-type">from here</a>, but it does not serve my purpose:</p>
<pre><code> echo '<pre>';
print_r(get_post_custom($post_id));
echo '</pre>';
</code></pre>
| [
{
"answer_id": 261069,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 3,
"selected": true,
"text": "<p>Add the following code in the functions.php</p>\n\n<p><strong>for acf</strong></p>\n\n<pre><code>functi... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115277/"
] | I have several post types. I want to get all custom fields associated with that post type.
Example:
```
Post
-- image
-- Featured image
-- body
```
I need to get all fields or custom fields in array. I found a solution [from here](https://wordpress.stackexchange.com/questions/18318/how-to-display-all-custom-fields-associated-with-a-post-type), but it does not serve my purpose:
```
echo '<pre>';
print_r(get_post_custom($post_id));
echo '</pre>';
``` | Add the following code in the functions.php
**for acf**
```
function get_all_meta($type){
global $wpdb;
$result = $wpdb->get_results($wpdb->prepare(
"SELECT post_id,meta_key,meta_value FROM wp_posts,wp_postmeta WHERE post_type = %s
AND wp_posts.ID = wp_postmeta.post_id", $type
), ARRAY_A);
return $result;
}
function acf(){
$options = array();
$acf = get_all_meta('acf');
foreach($acf as $key => $value){
$options['post_type'][$value['post_id']]['post_id'] = $value['post_id'];
$test = substr($value['meta_key'], 0, 6);
if($test === 'field_'){
$post_types = maybe_unserialize( $value['meta_value'] );
$options['post_type'][$value['post_id']]['key'][] = $post_types['key'];
$options['post_type'][$value['post_id']]['key'][] = $post_types['name'];
$options['post_type'][$value['post_id']]['key'][] = $post_types['type'];
}
if($value['meta_key'] == 'rule'){
$post_types = maybe_unserialize( $value['meta_value'] );
$options['post_type'][$value['post_id']]['post_types'] = $post_types['value'];
}
}
return $options;
}
```
This will give you the array value of post meta key for acf.
**How to use**
```
foreach(acf() as $key => $value){
update_post_meta(76, $value['type'], 'Steve');
}
```
**For pods**
function pods(){
global $wpdb;
//get the pods post types id.
```
$result = $wpdb->get_results($wpdb->prepare(
"SELECT ID,post_title,post_parent FROM wp_posts WHERE post_type = %s", $type
), ARRAY_A);
// pods each field for a post type create separate post type so again query to get the field post type result.
$pods_field_post_type = array();
foreach($result as $value){
$pods_field_post_type = $wpdb->get_results($wpdb->prepare(
"SELECT ID,post_title,post_name FROM wp_posts WHERE post_type = %s
AND post_parent = %d
", '_pods_field',$value["ID"]
), ARRAY_A);
}
$fields = array();
foreach($pods_field_post_type as key => $value):
$podsAPI = new PodsAPI();
$pod = $podsAPI->load_pod( array( 'name' => '
post' ));
$fields[] = $pod['fields'][$value['post_name']]['type'];
endforeach;
}
print_r($fields);
```
**How to use**
```
foreach($fields as $key => $value){
update_post_meta(76, $value, 'Steve');
}
```
function acf() and pods() give you the exact meta key of that post type.
If you copy and paste the code it may not work.
Hope this answer help you and also others.
let me know you not trouble anything. |
260,445 | <p>I am currently developing a theme where I want to add two permalinks.<br/>
One is redirecting to the index.php with some custom parameters and values (rule stored in the wp_options table), the other is redirecting to a file in my template which offers the admin-ajax.php functionality (rule stored in .htaccess file).</p>
<pre><code>add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'^(activate|reset)/([0-9]*)sfa([A-Za-z0-9]*)/?$',
'index.php?sfa_user=$matches[2]&sfa_password_reset=$matches[3]',
'top'
);
add_rewrite_rule(
'ajax-api/?$',
str_replace( ABSPATH, '', dirname( dirname( __FILE__ ) ) . '/api/ajax-api.php' )
);
flush_rewrite_rules( true );
} );
</code></pre>
<p>As I am in developement mode I am flushing the rules by executing on the 'init' hook as well <br/>(<em>I know this is bad practice but this seems to be the best method for me to check if there is any change in the .htaccess file.</em>).
<p></p><strong>The Problem:</strong><br/>
Even though <code>flush_rewrite_rules()</code> resets hard flushing by default I set the parameter to true just to make sure. My first rewrite rule is perfoming very well whereas the .htaccess file is not regenerated until I visit the options-permalink.php page in the backend (where the flush-function is called as well and works?!).</p>
<p></p>
<p>I already tried excecuting <code>flush_rewrite_rules()</code> on another hooks as proposed in the Reference.</p>
<p></p>
<p>Thanks in advance for your help!</p>
<p></p>
<p><strong>Edit:</strong><br/>
Even changing the code to the following did behave the same way…</p>
<pre><code>global $wp_rewrite;
$wp_rewrite->add_rule( '^(activate|reset)/([0-9]*)sfa([A-Za-z0-9]*)/?$', 'index.php?sfa_user=$matches[2]&sfa_password_reset=$matches[3]', 'top' );
$wp_rewrite->add_external_rule( 'ajax-api/?$', str_replace( ABSPATH, '', dirname( dirname( __FILE__ ) ) . '/api/ajax-api.php' ) );
$wp_rewrite->flush_rules( true );
</code></pre>
| [
{
"answer_id": 261069,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 3,
"selected": true,
"text": "<p>Add the following code in the functions.php</p>\n\n<p><strong>for acf</strong></p>\n\n<pre><code>functi... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115634/"
] | I am currently developing a theme where I want to add two permalinks.
One is redirecting to the index.php with some custom parameters and values (rule stored in the wp\_options table), the other is redirecting to a file in my template which offers the admin-ajax.php functionality (rule stored in .htaccess file).
```
add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'^(activate|reset)/([0-9]*)sfa([A-Za-z0-9]*)/?$',
'index.php?sfa_user=$matches[2]&sfa_password_reset=$matches[3]',
'top'
);
add_rewrite_rule(
'ajax-api/?$',
str_replace( ABSPATH, '', dirname( dirname( __FILE__ ) ) . '/api/ajax-api.php' )
);
flush_rewrite_rules( true );
} );
```
As I am in developement mode I am flushing the rules by executing on the 'init' hook as well
(*I know this is bad practice but this seems to be the best method for me to check if there is any change in the .htaccess file.*).
**The Problem:**
Even though `flush_rewrite_rules()` resets hard flushing by default I set the parameter to true just to make sure. My first rewrite rule is perfoming very well whereas the .htaccess file is not regenerated until I visit the options-permalink.php page in the backend (where the flush-function is called as well and works?!).
I already tried excecuting `flush_rewrite_rules()` on another hooks as proposed in the Reference.
Thanks in advance for your help!
**Edit:**
Even changing the code to the following did behave the same way…
```
global $wp_rewrite;
$wp_rewrite->add_rule( '^(activate|reset)/([0-9]*)sfa([A-Za-z0-9]*)/?$', 'index.php?sfa_user=$matches[2]&sfa_password_reset=$matches[3]', 'top' );
$wp_rewrite->add_external_rule( 'ajax-api/?$', str_replace( ABSPATH, '', dirname( dirname( __FILE__ ) ) . '/api/ajax-api.php' ) );
$wp_rewrite->flush_rules( true );
``` | Add the following code in the functions.php
**for acf**
```
function get_all_meta($type){
global $wpdb;
$result = $wpdb->get_results($wpdb->prepare(
"SELECT post_id,meta_key,meta_value FROM wp_posts,wp_postmeta WHERE post_type = %s
AND wp_posts.ID = wp_postmeta.post_id", $type
), ARRAY_A);
return $result;
}
function acf(){
$options = array();
$acf = get_all_meta('acf');
foreach($acf as $key => $value){
$options['post_type'][$value['post_id']]['post_id'] = $value['post_id'];
$test = substr($value['meta_key'], 0, 6);
if($test === 'field_'){
$post_types = maybe_unserialize( $value['meta_value'] );
$options['post_type'][$value['post_id']]['key'][] = $post_types['key'];
$options['post_type'][$value['post_id']]['key'][] = $post_types['name'];
$options['post_type'][$value['post_id']]['key'][] = $post_types['type'];
}
if($value['meta_key'] == 'rule'){
$post_types = maybe_unserialize( $value['meta_value'] );
$options['post_type'][$value['post_id']]['post_types'] = $post_types['value'];
}
}
return $options;
}
```
This will give you the array value of post meta key for acf.
**How to use**
```
foreach(acf() as $key => $value){
update_post_meta(76, $value['type'], 'Steve');
}
```
**For pods**
function pods(){
global $wpdb;
//get the pods post types id.
```
$result = $wpdb->get_results($wpdb->prepare(
"SELECT ID,post_title,post_parent FROM wp_posts WHERE post_type = %s", $type
), ARRAY_A);
// pods each field for a post type create separate post type so again query to get the field post type result.
$pods_field_post_type = array();
foreach($result as $value){
$pods_field_post_type = $wpdb->get_results($wpdb->prepare(
"SELECT ID,post_title,post_name FROM wp_posts WHERE post_type = %s
AND post_parent = %d
", '_pods_field',$value["ID"]
), ARRAY_A);
}
$fields = array();
foreach($pods_field_post_type as key => $value):
$podsAPI = new PodsAPI();
$pod = $podsAPI->load_pod( array( 'name' => '
post' ));
$fields[] = $pod['fields'][$value['post_name']]['type'];
endforeach;
}
print_r($fields);
```
**How to use**
```
foreach($fields as $key => $value){
update_post_meta(76, $value, 'Steve');
}
```
function acf() and pods() give you the exact meta key of that post type.
If you copy and paste the code it may not work.
Hope this answer help you and also others.
let me know you not trouble anything. |
260,465 | <p>I'm really new to wordpress and now I have to do a plugin that creates a HTML table from file and prints it to the page, and add more functionality to the table using DataTables jquery addon. This all has to happen when i call shortcode in the page. I have managed to get the html table to the page, but i have no idea how to run jquery script to modify it.
So, in short: how to run jquery script after shortcode.
Any input is appreciated!</p>
| [
{
"answer_id": 260468,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function your_css_and_js() {\n wp_register_style('your_css_and_js', plugins_url('style.css',__FILE_... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115640/"
] | I'm really new to wordpress and now I have to do a plugin that creates a HTML table from file and prints it to the page, and add more functionality to the table using DataTables jquery addon. This all has to happen when i call shortcode in the page. I have managed to get the html table to the page, but i have no idea how to run jquery script to modify it.
So, in short: how to run jquery script after shortcode.
Any input is appreciated! | Your question is a little unclear. I'm interpreting it to mean that you want to enqueue a jQuery script to be run by the user's browser only on public pages that contain the shortcode.
There are (at least) three ways of running a jQuery script only on pages that have a specific shortcode. The first way is to use the `add_shortcode()` function to add a hook to `get_footer` which then enqueues the jQuery script in the footer.
```
//* Enqueue script in the footer
function wpse_260465_enqueue_script() {
wp_enqueue_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );
}
//* Add action to enqueue script in the footer and return shortcode value
function wpse_260465_shortcode( $atts ) {
add_action( 'get_footer', 'wpse_260465_enqueue_script' );
return 'your shortcode content';
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
```
The second way registers the script on every page, but only enqueues it when the specific shortcode is called on a page.
```
//* Enqueue previously registered script and return shortcode value
function wpse_260465_shortcode( $atts ) {
wp_enqueue_script( 'your-style-id' );
return 'your shortcode content';
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
//* Register our script to maybe enqueue later
add_action( 'wp_enqueue_scripts', 'wpse_260465_enqueue_scripts' );
function wpse_260465_enqueue_scripts() {
wp_register_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );
}
```
The third way is to simply use the `add_shortcode()` function to write the jQuery inline.
```
//* Return inline jQuery script with shortcode value
function wpse_260465_shortcode( $atts ) {
$your_shortcode_content = 'your shortcode content';
$your_shortcode_content .= $your_inline_jquery;
return $your_shortcode_content;
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
```
The first and second methods are more the "WordPress way", and the third is the easiest to understand, but all three should work. |
260,488 | <p>I have a normal WordPress settings page. It POSTs to options.php.</p>
<p>In options.php it uses wp_get_referer to redirect back to the page it came from.</p>
<p>I need to use remove_query_arg to remove an argument from the URL. Example:</p>
<pre><code>https://www.example.com/wp-admin/admin.php?page=plugin_settings_page&tab=90
</code></pre>
<p>I need to remove the tab=90 part. How can I do this via options.php?</p>
| [
{
"answer_id": 260468,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function your_css_and_js() {\n wp_register_style('your_css_and_js', plugins_url('style.css',__FILE_... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112235/"
] | I have a normal WordPress settings page. It POSTs to options.php.
In options.php it uses wp\_get\_referer to redirect back to the page it came from.
I need to use remove\_query\_arg to remove an argument from the URL. Example:
```
https://www.example.com/wp-admin/admin.php?page=plugin_settings_page&tab=90
```
I need to remove the tab=90 part. How can I do this via options.php? | Your question is a little unclear. I'm interpreting it to mean that you want to enqueue a jQuery script to be run by the user's browser only on public pages that contain the shortcode.
There are (at least) three ways of running a jQuery script only on pages that have a specific shortcode. The first way is to use the `add_shortcode()` function to add a hook to `get_footer` which then enqueues the jQuery script in the footer.
```
//* Enqueue script in the footer
function wpse_260465_enqueue_script() {
wp_enqueue_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );
}
//* Add action to enqueue script in the footer and return shortcode value
function wpse_260465_shortcode( $atts ) {
add_action( 'get_footer', 'wpse_260465_enqueue_script' );
return 'your shortcode content';
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
```
The second way registers the script on every page, but only enqueues it when the specific shortcode is called on a page.
```
//* Enqueue previously registered script and return shortcode value
function wpse_260465_shortcode( $atts ) {
wp_enqueue_script( 'your-style-id' );
return 'your shortcode content';
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
//* Register our script to maybe enqueue later
add_action( 'wp_enqueue_scripts', 'wpse_260465_enqueue_scripts' );
function wpse_260465_enqueue_scripts() {
wp_register_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );
}
```
The third way is to simply use the `add_shortcode()` function to write the jQuery inline.
```
//* Return inline jQuery script with shortcode value
function wpse_260465_shortcode( $atts ) {
$your_shortcode_content = 'your shortcode content';
$your_shortcode_content .= $your_inline_jquery;
return $your_shortcode_content;
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
```
The first and second methods are more the "WordPress way", and the third is the easiest to understand, but all three should work. |
260,500 | <p>I am trying to insert this meta information into the cart and checkout page for woocommerce. It will hide a specific plugin on those pages. However i know if i edit the plugin files for woocommerce it will be overwritten on woocommerce update.</p>
<p>How would i do that correctly? Jquery? Or even function.php function? </p>
<pre><code>if (wc_get_page_id( 'cart' ) == get_the_ID()) {
<meta name="yo:active" content="false">
}
</code></pre>
<p>or</p>
<pre><code>if !is_page(array('cart', 'checkout')) {
$('#yoHolder').attr("style", "display: none !important");
}
</code></pre>
<p>i tried this too to achieve same outcome of hiding it but didnt work. </p>
<p>Thanks for any help!</p>
| [
{
"answer_id": 260765,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 1,
"selected": false,
"text": "<p>Add the code to the file functions.php</p>\n\n<pre><code>/**\n * add data in cart \n * \n */\nfunction add_... | 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260500",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110570/"
] | I am trying to insert this meta information into the cart and checkout page for woocommerce. It will hide a specific plugin on those pages. However i know if i edit the plugin files for woocommerce it will be overwritten on woocommerce update.
How would i do that correctly? Jquery? Or even function.php function?
```
if (wc_get_page_id( 'cart' ) == get_the_ID()) {
<meta name="yo:active" content="false">
}
```
or
```
if !is_page(array('cart', 'checkout')) {
$('#yoHolder').attr("style", "display: none !important");
}
```
i tried this too to achieve same outcome of hiding it but didnt work.
Thanks for any help! | If your goal is to put it in the `<head>IM INSIDE THE HEAD</head>` tag than just put it inside the head tag in the `theme_header.php` or `header.php` of your theme – if it's not a child theme.
Place this snippet of code directly above the closing `</head>` tag in your header.php file.
```
<?php
if ( is_checkout() || is_cart() ) {
// Add meta tag here
echo '<meta name="yo:active" content="false">';
}
?>
```
Should work fine for you. |
260,507 | <p>I have a list of terms I'm displaying using "get_terms". Each term is linked so if the user clicks it, they go to the term archive page. </p>
<pre><code> <?php $terms = get_terms('category');t
echo '<ul>';
foreach ($terms as $term) {
echo '<li><a href="'.get_term_link($term).'">'.$term->name.'</a></li>';
}
echo '</ul>';
?>
</code></pre>
<p>However, I would like to know if there's a way to add an "active" class to each term link if user goes to the term archive page. </p>
<p>Thanks a lot for your help,</p>
| [
{
"answer_id": 260508,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 3,
"selected": false,
"text": "<p>Run a conditional check in the <code>foreach</code> loop using <code>is_category($term-name)</code></p>\n\n<p>Ass... | 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260507",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21245/"
] | I have a list of terms I'm displaying using "get\_terms". Each term is linked so if the user clicks it, they go to the term archive page.
```
<?php $terms = get_terms('category');t
echo '<ul>';
foreach ($terms as $term) {
echo '<li><a href="'.get_term_link($term).'">'.$term->name.'</a></li>';
}
echo '</ul>';
?>
```
However, I would like to know if there's a way to add an "active" class to each term link if user goes to the term archive page.
Thanks a lot for your help, | Run a conditional check in the `foreach` loop using `is_category($term-name)`
Assign a class variable to `active` if it's the same as `$term->name`
```
$terms = get_terms( 'category' );
echo '<ul>';
foreach ( $terms as $term ) {
$class = ( is_category( $term->name ) ) ? 'active' : ''; // assign this class if we're on the same category page as $term->name
echo '<li><a href="' . get_term_link( $term ) . '" class="' . $class . '">' . $term->name . '</a></li>';
}
echo '</ul>';
``` |
260,512 | <p>I am somewhat new in WordPress if it is about "deeper" customization.</p>
<p>Now I am having this function:</p>
<pre><code>esc_html_e( 'Dear Guest, with Your information we not find any room at the moment. Please contact us per email info@whitesandsamuiresort.com.', 'awebooking' );
</code></pre>
<p>And the text is showing so far.</p>
<p>But what <em>function</em> do I need to use when I like to add an <code>a</code> <code>href</code> (HTML link)?</p>
<p>So I like to have this text:</p>
<blockquote>
<p>Dear Guest, with Your information we not find any room at the moment.</p>
<p>Please contact us on our <code><a href="http://www.whitesandsamuiresort.com/contact-us/">contact page</a></code> or per email <code>info@whitesandsamuiresort.com</code>.</p>
</blockquote>
<p>I'm having problem supporting translation (internationalization / localization) and escaping HTML links at the same time.</p>
| [
{
"answer_id": 260513,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using esc_html_e then this function simply says it escapes the HTML tags. So you can't be able to u... | 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260512",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115691/"
] | I am somewhat new in WordPress if it is about "deeper" customization.
Now I am having this function:
```
esc_html_e( 'Dear Guest, with Your information we not find any room at the moment. Please contact us per email info@whitesandsamuiresort.com.', 'awebooking' );
```
And the text is showing so far.
But what *function* do I need to use when I like to add an `a` `href` (HTML link)?
So I like to have this text:
>
> Dear Guest, with Your information we not find any room at the moment.
>
>
> Please contact us on our `<a href="http://www.whitesandsamuiresort.com/contact-us/">contact page</a>` or per email `info@whitesandsamuiresort.com`.
>
>
>
I'm having problem supporting translation (internationalization / localization) and escaping HTML links at the same time. | Since [`esc_html_e`](https://developer.wordpress.org/reference/functions/esc_html_e/) will escape HTML link (hence will show the HTML anchor as plain text), you'll need to segment the text and escape the non-HTML part with `esc_html_e` or [`esc_html__`](https://developer.wordpress.org/reference/functions/esc_html__/), and print the HTML LINK part without HTML escaping.
Method-1 (just for your understanding):
=======================================
You may do it in parts, like this:
```
esc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );
echo "<br><br>";
printf(
esc_html__( '%1$s %2$s', 'text-domain' ),
esc_html__( 'Please contact us on our', 'text-domain' ),
sprintf(
'<a href="%s">%s</a>',
esc_url( 'http://www.example.com/contact-us/' ),
esc_html__( 'Contact Page', 'text-domain' )
)
);
printf(
' or <a href="%s">%s</a>',
esc_url( 'mailto:info@example.com', array( 'mailto' ) ),
esc_html__( 'Email', 'text-domain' )
);
```
Method-2 (just for your understanding):
=======================================
Obviously, different languages will have different ordering of texts, so to give translators more flexibility (with escaping and ordering of text), you may do it in the following way instead:
```
printf(
esc_html__( '%1$s%2$s%3$s%4$s%5$s', 'text-domain' ),
esc_html__( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' ),
nl2br( esc_html__( "\n\n", 'text-domain' ) ),
sprintf(
esc_html__( '%1$s %2$s', 'text-domain' ),
esc_html__( 'Please contact us on our', 'text-domain' ),
sprintf(
'<a href="%s">%s</a>',
esc_url( 'http://www.example.com/contact-us/' ),
esc_html__( 'Contact Page', 'text-domain' )
)
),
esc_html__( ' or ', 'text-domain' ),
sprintf(
'<a href="%s">%s</a>',
esc_url( 'mailto:info@example.com', array( 'mailto' ) ),
esc_html__( 'Email', 'text-domain' )
)
);
```
This way of doing it will:
1. Escape all the necessary translated texts.
2. Allow the HTML for link, email (with `mailto:` syntax) etc.
3. Allow translators to have all sorts of different ordering of texts for different languages. The [argument swapping notation](http://php.net/manual/en/function.sprintf.php#example-5474) (`%1$s`, `%2$s` etc.) is used so that the translators may reorder the translated text where needed.
---
Method-3 (Updated & Recommended):
=================================
As [@shea rightly pointed out](https://wordpress.stackexchange.com/a/261374/110572), **Method-2** above works fine, but it may be difficult for the translators to add support for different languages. So we need a solution that:
1. Keeps the sentences intact (doesn't break sentences).
2. Does proper escaping.
3. Provides ways to have different ordering for contact & email links (or anything similar) within the translated sentence.
So to avoid the complication of **method-2**, the solution below keeps the translatable sentences intact and does the proper URL escaping & argument swapping at the same time (more notes within CODE comments):
```
// sample contact url (may be from an unsafe place like user input)
$contact_url = 'http://www.example.com/contact-us/';
// escaping $contact_url
$contact_url = esc_url( $contact_url );
// sample contact email (may be from an unsafe place like user input)
$contact_email = 'info@example.com';
// escaping, sanitizing & hiding $contact_email.
// Yes, you may still need to sanitize & escape email while using antispambot() function
$contact_email = esc_url( sprintf( 'mailto:%s', antispambot( sanitize_email( $contact_email ) ) ), array( 'mailto' ) );
esc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );
echo "<br><br>";
printf(
esc_html__( 'Please contact us on our %1$s or per %2$s.', 'text-domain' ),
sprintf(
'<a href="%s">%s</a>',
$contact_url,
esc_html__( 'Contact Page', 'text-domain' )
),
sprintf(
'<a href="%s">%s</a>',
$contact_email,
esc_html__( 'Email', 'text-domain' )
)
);
```
This way of doing it will give translators two full sentences & two separate words to translate. So a translators will only have to worry about the following simple lines (while the CODE takes care of the rest):
```
esc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );
// ...
esc_html__( 'Please contact us on our %1$s or per %2$s', 'text-domain' )
// ...
esc_html__( 'Contact Page', 'text-domain' )
// ...
esc_html__( 'Email', 'text-domain' )
```
That's it, simple structure and does proper escaping and argument swapping as well.
---
Read more about [internationalization for themes](https://developer.wordpress.org/themes/functionality/internationalization/) & [internationalization for plugins](https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/). |
260,519 | <p>I want to be able to detect if a file at a certain path is a WordPress generated thumbnail. The only distinguishing feature of the WordPress thumbnail, as far as individual files are concerned, is that it would end with two or three numbers, 'x', another two or three numbers and then the file extension. The only way I can think of doing this would be to use a regex to literally detect that pattern in the file name. Is there a better way that I'm not thinking of? If not can someone help me with the regex?</p>
| [
{
"answer_id": 260543,
"author": "Irene Mitchell",
"author_id": 108769,
"author_profile": "https://wordpress.stackexchange.com/users/108769",
"pm_score": 2,
"selected": false,
"text": "<p>You need to know your site's current thumbnail dimension settings in order for you to detect if the ... | 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260519",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96964/"
] | I want to be able to detect if a file at a certain path is a WordPress generated thumbnail. The only distinguishing feature of the WordPress thumbnail, as far as individual files are concerned, is that it would end with two or three numbers, 'x', another two or three numbers and then the file extension. The only way I can think of doing this would be to use a regex to literally detect that pattern in the file name. Is there a better way that I'm not thinking of? If not can someone help me with the regex? | You need to know your site's current thumbnail dimension settings in order for you to detect if the $url is of thumbnail size.
```
$thumbnail_width = get_option( 'thumbnail_size_w' );
$thumbnail_height = get_option( 'thumbnail_size_h' );
// The do detection
// Assuming you have the image $url
$pattern = '%' . $thumbnail_width . 'x' . $thumbnail_height . '%';
if ( preg_match( $pattern, $url ) ) {
// do your stuff here ...
}
``` |
260,523 | <p>It is possible set display name from entered string into nickname registration field? I trying do this with simple hook, but after all it is not work.</p>
<pre><code>function set_default_display_name( $user_id ) {
$user = get_userdata( $user_id );
$name = $user->nickname;
$args = array(
'ID' => $user_id,
'display_name' => $name
);
wp_update_user( $args );
}
add_action( 'user_register', 'set_default_display_name' );
</code></pre>
<p>By default, immediately after registration, display name was set from WP username (login) not nickname. Can sombody help me to set a display name from nickname?</p>
| [
{
"answer_id": 260543,
"author": "Irene Mitchell",
"author_id": 108769,
"author_profile": "https://wordpress.stackexchange.com/users/108769",
"pm_score": 2,
"selected": false,
"text": "<p>You need to know your site's current thumbnail dimension settings in order for you to detect if the ... | 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84343/"
] | It is possible set display name from entered string into nickname registration field? I trying do this with simple hook, but after all it is not work.
```
function set_default_display_name( $user_id ) {
$user = get_userdata( $user_id );
$name = $user->nickname;
$args = array(
'ID' => $user_id,
'display_name' => $name
);
wp_update_user( $args );
}
add_action( 'user_register', 'set_default_display_name' );
```
By default, immediately after registration, display name was set from WP username (login) not nickname. Can sombody help me to set a display name from nickname? | You need to know your site's current thumbnail dimension settings in order for you to detect if the $url is of thumbnail size.
```
$thumbnail_width = get_option( 'thumbnail_size_w' );
$thumbnail_height = get_option( 'thumbnail_size_h' );
// The do detection
// Assuming you have the image $url
$pattern = '%' . $thumbnail_width . 'x' . $thumbnail_height . '%';
if ( preg_match( $pattern, $url ) ) {
// do your stuff here ...
}
``` |
260,535 | <p>I am trying to add theme support for custom background using the following code in functions.php file:</p>
<pre><code>function supp_custom_bg() {
$defaults = array(
'default-color' => '',
'default-image' => '',
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
);
add_theme_support( 'custom-background', $defaults );
}
add_action( 'after_setup_theme', 'supp_custom_bg', 20 );
</code></pre>
<p>and the options now are activated in the customizer but no effect on the theme.</p>
<p>Note: The <code>wp_head</code> is added to the <code><head></code> tag</p>
| [
{
"answer_id": 260541,
"author": "Irene Mitchell",
"author_id": 108769,
"author_profile": "https://wordpress.stackexchange.com/users/108769",
"pm_score": 0,
"selected": false,
"text": "<p>If you intend to customize how background image is implemented in your theme then do share the code ... | 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109616/"
] | I am trying to add theme support for custom background using the following code in functions.php file:
```
function supp_custom_bg() {
$defaults = array(
'default-color' => '',
'default-image' => '',
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
);
add_theme_support( 'custom-background', $defaults );
}
add_action( 'after_setup_theme', 'supp_custom_bg', 20 );
```
and the options now are activated in the customizer but no effect on the theme.
Note: The `wp_head` is added to the `<head>` tag | The simplest way to use this feature:
1. Add `add_theme_support( 'custom-background' );` to `functions.php`
2. Use `body_class()` in your `body` tag like this: `<body <?php body_class(); ?>>`
3. use `<?php wp_head(); ?>` in your `head` tag
if you go to the customizer should look like this:
[](https://i.stack.imgur.com/59c9D.png) |
260,553 | <p>I'm trying to add url query parameters to all internal links inside a WordPress blog. For example, client lands on the blog with this link:</p>
<pre><code>www.example.com/?p1=test&p2=test
</code></pre>
<p>I want the links inside the blog, for example a link to a post, to still have the query strings:</p>
<pre><code>www.example.com/post1/?p1=test&p2=test
</code></pre>
<p>Is there is a way to do it?</p>
| [
{
"answer_id": 260554,
"author": "AppError",
"author_id": 113811,
"author_profile": "https://wordpress.stackexchange.com/users/113811",
"pm_score": 0,
"selected": false,
"text": "<p>So you want to \"keep\" the variable value? Maybe you're best to set a cookie? This would probably make th... | 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260553",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115654/"
] | I'm trying to add url query parameters to all internal links inside a WordPress blog. For example, client lands on the blog with this link:
```
www.example.com/?p1=test&p2=test
```
I want the links inside the blog, for example a link to a post, to still have the query strings:
```
www.example.com/post1/?p1=test&p2=test
```
Is there is a way to do it? | The following is **not** a *complete* solution (i.e., as @cjbj mentioned, it won't handle links in post content), but it will achieve what you want for any link whose URL is obtained (in WP Core, a theme or a plugin) via [get\_permalink()](https://developer.wordpress.org/reference/functions/get_permalink/) (including the output of [wp\_page\_menu()](https://developer.wordpress.org/reference/functions/wp_page_menu/), and kin).
```
$filters = array (
'post_link', // when post_type == 'post'
'page_link', // when post_type == 'page'
'attachment_link', // when post_type == 'attachment'
'post_type_link', // when post_type is not one of the above
) ;
foreach ($filters as $filter) {
add_filter ($filter, 'wpse_add_current_requests_query_args', 10, 3) ;
}
function
wpse_add_current_requests_query_args ($permalink, $post, $leavename)
{
if (!is_admin ()) {
// we only want to modify the permalink URL on the front-end
return ;
}
// for the purposes of this answer, we ignore the $post & $leavename
// params, but they are there in case you want to do conditional
// processing based on their value
return (esc_url (add_query_arg ($_GET, $permalink))) ;
}
```
Explanation
-----------
Before returning it's result, `get_permalink()` applies one of 4 filters (named in the `$filters` array above) on the permalink it has generated. So, we hook into each of those filters.
The function we hook to these filters calls [add\_query\_arg()](https://developer.wordpress.org/reference/functions/add_query_arg/) to add any query args present in the current request (i.e., `$_GET`).
Important Security Consideration
--------------------------------
As mentioned in [add\_query\_arg()](https://developer.wordpress.org/reference/functions/add_query_arg/):
>
> Important: The return value of add\_query\_arg() is not escaped by default. Output should be late-escaped with esc\_url() or similar to help prevent vulnerability to cross-site scripting (XSS) attacks.
>
>
>
Calling esc\_url() in `wpse_add_current_requests_query_args()` is not what I would call "late-escaped" in all cases. But unfortunately, a number of WP Core funcs (e.g. [Walker\_Page::start\_el()](https://developer.wordpress.org/reference/classes/walker_page/start_el/), which is ultimately called by `wp_page_menu()`), don't call `esc_url()` on the return value of `get_permalink()`, so we have to call it in our filter hook to be safe. |
260,586 | <p>I am trying to figure out a way to make a sum of all the posts displayed in a loop. For example:</p>
<pre><code><?php if (have_posts()) :
$total_count = 1;
while (have_posts()) : the_post();
echo $total_count;
endwhile;
endif;
?>
</code></pre>
<p>Returns: 1 1 1 1 1 1 1</p>
<p>Since there are 7 posts in my loop. However, I would like to make a sum of all those 1's in order to get 7 as a result.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 260587,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>If <code>have_posts()</code> is <code>true</code>, there is a global <code>WP_Query</code> object available. And that... | 2017/03/19 | [
"https://wordpress.stackexchange.com/questions/260586",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21245/"
] | I am trying to figure out a way to make a sum of all the posts displayed in a loop. For example:
```
<?php if (have_posts()) :
$total_count = 1;
while (have_posts()) : the_post();
echo $total_count;
endwhile;
endif;
?>
```
Returns: 1 1 1 1 1 1 1
Since there are 7 posts in my loop. However, I would like to make a sum of all those 1's in order to get 7 as a result.
Any ideas? | If `have_posts()` is `true`, there is a global `WP_Query` object available. And that has a post count already:
```
if ( have_posts() )
{
print $GLOBALS['wp_query']->post_count;
}
```
There is no need for a custom count. |
260,596 | <p>Is this possible with a tinymce plugin? I think other ways to access the iframe are not working or not recommended.</p>
<p>I have <a href="https://www.tinymce.com/docs/api/tinymce.dom/tinymce.dom.domquery/" rel="nofollow noreferrer">found this</a> And tried that in the printing mce plugin <a href="https://plugins.trac.wordpress.org/browser/tinymce-advanced/tags/4.4.3/mce/print/plugin.js" rel="nofollow noreferrer">inside the TinyMCE Advanced plugin but it does not work</a>.</p>
<pre><code>var $ = tinymce.dom.DomQuery;
$('p').attr('attr', 'value').addClass('class');
</code></pre>
<p>I have installed the tinymce advanced plugin and tryed adding this lines to the print plugin. The plugin gets executed, the print dialog opens but it just does not to anything to the dom. Does WP has the full version of tinymce?</p>
<pre><code>/**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
var mce_dom = tinymce.dom.DomQuery;
mce_dom('p').attr('id', 'arve').addClass('arve-html-class');
mce_dom('html').attr('id', 'arve').addClass('arve-html-class');
tinymce.PluginManager.add('print', function(editor) {
var mce_dom = tinymce.dom.DomQuery;
mce_dom('p').attr('id', 'arve').addClass('arve-html-class');
mce_dom('html').attr('id', 'arve').addClass('arve-html-class');
editor.addCommand('mcePrint', function() {
editor.getWin().print();
});
editor.addButton('print', {
title: 'Print',
cmd: 'mcePrint'
});
editor.addShortcut('Meta+P', '', 'mcePrint');
editor.addMenuItem('print', {
text: 'Print',
cmd: 'mcePrint',
icon: 'print',
shortcut: 'Meta+P',
context: 'file'
});
});
</code></pre>
| [
{
"answer_id": 262238,
"author": "Abhishek Pandey",
"author_id": 114826,
"author_profile": "https://wordpress.stackexchange.com/users/114826",
"pm_score": 3,
"selected": true,
"text": "<p>Hope You can use fallowing </p>\n\n<pre><code>// Sets class attribute on all paragraphs in the activ... | 2017/03/19 | [
"https://wordpress.stackexchange.com/questions/260596",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38602/"
] | Is this possible with a tinymce plugin? I think other ways to access the iframe are not working or not recommended.
I have [found this](https://www.tinymce.com/docs/api/tinymce.dom/tinymce.dom.domquery/) And tried that in the printing mce plugin [inside the TinyMCE Advanced plugin but it does not work](https://plugins.trac.wordpress.org/browser/tinymce-advanced/tags/4.4.3/mce/print/plugin.js).
```
var $ = tinymce.dom.DomQuery;
$('p').attr('attr', 'value').addClass('class');
```
I have installed the tinymce advanced plugin and tryed adding this lines to the print plugin. The plugin gets executed, the print dialog opens but it just does not to anything to the dom. Does WP has the full version of tinymce?
```
/**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
var mce_dom = tinymce.dom.DomQuery;
mce_dom('p').attr('id', 'arve').addClass('arve-html-class');
mce_dom('html').attr('id', 'arve').addClass('arve-html-class');
tinymce.PluginManager.add('print', function(editor) {
var mce_dom = tinymce.dom.DomQuery;
mce_dom('p').attr('id', 'arve').addClass('arve-html-class');
mce_dom('html').attr('id', 'arve').addClass('arve-html-class');
editor.addCommand('mcePrint', function() {
editor.getWin().print();
});
editor.addButton('print', {
title: 'Print',
cmd: 'mcePrint'
});
editor.addShortcut('Meta+P', '', 'mcePrint');
editor.addMenuItem('print', {
text: 'Print',
cmd: 'mcePrint',
icon: 'print',
shortcut: 'Meta+P',
context: 'file'
});
});
``` | Hope You can use fallowing
```
// Sets class attribute on all paragraphs in the active editor
tinymce.activeEditor.dom.setAttrib(tinymce.activeEditor.dom.select('p'), 'class', 'myclass');
// Sets class attribute on a specific element in the current page
tinymce.dom.setAttrib('mydiv', 'class', 'myclass');
```
or You can add Id by jquery like this
`$('div').find('p').attr('id', 'myid');` |
260,615 | <p>I have on my page section with randomly selected posts via <code>new WP_Query</code>. The problem is that <code>'posts_per_page'</code> attribute don't work. Here is my code:</p>
<pre><code><div id="featured">
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 4,
'nopaging' => true,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<div style="table full">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<div class="featcell" style="background: url(<?php the_post_thumbnail_url(); ?>) center center">
<a class="featartlink" href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a>
</div>
<?php
}
echo '</div>';
wp_reset_postdata();
}
?>
</div>
</code></pre>
<p>The result of script above is that script loading all posts from database. Script is placed under post on single post page. What i doing wrong? It appears that all is OK, but it is not! Thank You for help.</p>
| [
{
"answer_id": 260617,
"author": "X9DESIGN",
"author_id": 84343,
"author_profile": "https://wordpress.stackexchange.com/users/84343",
"pm_score": 1,
"selected": false,
"text": "<p>I dont why, but after some tests i trying to use also <code>get_posts()</code> function and all is works fin... | 2017/03/19 | [
"https://wordpress.stackexchange.com/questions/260615",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84343/"
] | I have on my page section with randomly selected posts via `new WP_Query`. The problem is that `'posts_per_page'` attribute don't work. Here is my code:
```
<div id="featured">
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 4,
'nopaging' => true,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<div style="table full">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<div class="featcell" style="background: url(<?php the_post_thumbnail_url(); ?>) center center">
<a class="featartlink" href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a>
</div>
<?php
}
echo '</div>';
wp_reset_postdata();
}
?>
</div>
```
The result of script above is that script loading all posts from database. Script is placed under post on single post page. What i doing wrong? It appears that all is OK, but it is not! Thank You for help. | `nopaging` disables pagination, and `posts_per_page` is a pagination parameter. You are telling it to ignore pagination and return all posts. |
260,620 | <p>I'm trying to add a CSS class to a comment and everything seems to work if the comment id was hard coded in. However it's not working because I don't know how to get the comment id and then from there, get the comment meta stored in the database.</p>
<p>in <code>wp_commentmeta</code> I have the following data:</p>
<pre><code>meta_id
1
comment_id
10
meta_key
score
meta_value
0.25
</code></pre>
<p>I then have this code using a filter hook to add the class to the list of comment classes. However, this is in a standalone plugin in the /wp-content/plugins folder and I need to loop through all the comments for that post.</p>
<pre><code>function add_comments_class( $classes, $class, $comment_ID, $comment, $post_id ) {
$meta_data = get_comment_meta( $comment_ID, 'score', true );
$meta_data = round((float)$meta_data * 100 );
$classes[] = $meta_data;
return $classes;
} add_filter( 'comment_class', 'add_comments_class' );
</code></pre>
<p>I've looked at <a href="https://codex.wordpress.org/Function_Reference/get_comment_meta" rel="nofollow noreferrer">the Codex</a> but that doesn't seem to identify how to get the ID when viewing a post etc.</p>
<p>The variables in the function were taken from <a href="https://wordpress.stackexchange.com/a/259336/111400">this answer here</a> although it doesn't explain why those specific variables are used or where they are from.</p>
| [
{
"answer_id": 260617,
"author": "X9DESIGN",
"author_id": 84343,
"author_profile": "https://wordpress.stackexchange.com/users/84343",
"pm_score": 1,
"selected": false,
"text": "<p>I dont why, but after some tests i trying to use also <code>get_posts()</code> function and all is works fin... | 2017/03/19 | [
"https://wordpress.stackexchange.com/questions/260620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I'm trying to add a CSS class to a comment and everything seems to work if the comment id was hard coded in. However it's not working because I don't know how to get the comment id and then from there, get the comment meta stored in the database.
in `wp_commentmeta` I have the following data:
```
meta_id
1
comment_id
10
meta_key
score
meta_value
0.25
```
I then have this code using a filter hook to add the class to the list of comment classes. However, this is in a standalone plugin in the /wp-content/plugins folder and I need to loop through all the comments for that post.
```
function add_comments_class( $classes, $class, $comment_ID, $comment, $post_id ) {
$meta_data = get_comment_meta( $comment_ID, 'score', true );
$meta_data = round((float)$meta_data * 100 );
$classes[] = $meta_data;
return $classes;
} add_filter( 'comment_class', 'add_comments_class' );
```
I've looked at [the Codex](https://codex.wordpress.org/Function_Reference/get_comment_meta) but that doesn't seem to identify how to get the ID when viewing a post etc.
The variables in the function were taken from [this answer here](https://wordpress.stackexchange.com/a/259336/111400) although it doesn't explain why those specific variables are used or where they are from. | `nopaging` disables pagination, and `posts_per_page` is a pagination parameter. You are telling it to ignore pagination and return all posts. |
260,652 | <p>I originally installed wordpress in a subdirectory called /blog. Today I decided to change the URL of my site to remove the /blog element from the URL e.g. from www.mywebsite.com/blog to www.mywebsite.com. Here is what I did:</p>
<ol>
<li>went to settings > general and changed the site address:</li>
</ol>
<p>WordPress Address (URL): www.mywebsite.com/blog</p>
<p>Site Address (URL): www.mywebsite.com</p>
<ol start="2">
<li><p>deleted my original homepage (index.html)</p></li>
<li><p>downloaded the index.php file from the /blog directory, and uploaded a copy into the root directory</p></li>
<li><p>opened the index.php file from the root directory and changed the following line of code:</p></li>
</ol>
<p><strike>require( dirname( <strong>FILE</strong> ) . '/wp-blog-header.php' );</strike></p>
<pre><code> require( dirname( __FILE__ ) . '/blog/wp-blog-header.php' );
</code></pre>
<p>This worked in that I now landed directly on my wordpress blog when I typed in www.mywebsite.com, but all my internal links resulted in 404 errors. So I changed my permalinks to plain (e.g. wwww.mywebsite.com/?p=123), which fixed the broken links. However, I prefer to use the post name structure (e.g. wwww.mywebsite.com/name-of-post) so tried to fix this by doing the following:</p>
<ol start="5">
<li><p>created a file called .htaccess in the root directory, and typed in the following code:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre></li>
</ol>
<p>This went horribly wrong, resulting in 500 errors that locked my out of the WP dashboard for some time. I can't remember exactly how I fixed this, but the only other change I made was as follows:</p>
<ol start="6">
<li><p>edited web.config file in /blog directory:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="WordPress Rule" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>"
</code></pre></li>
</ol>
<p>This still didn't allow post name permalinks, so I set permalinks back to plain. However, I now have a weird situation where about half of my internal links work okay, and the other half result in 404's. I don't really understand how this is possible, as I would have thought it would be all or nothing!</p>
<p>Can anyone please help?</p>
<p>UPDATE - NOW RESOLVED (YAY!):
After struggling to fix this, I contacted the support helpline for the company that provides my web hosting. They said that the fact I was on a windows server was problematic, as it is not really compatible with WordPress. So this is what I / they did:</p>
<ol>
<li>phoned my web host providers and changed to a LINUX server</li>
<li>downloaded the free FTP application FileZilla, and imported all of my wordpress files onto my computer. I then transferred them via FTP to the new LINUX server, into the root directory (public_html).</li>
<li>exported my WordPress database from the old windows server and saved onto my computer. I then created a new database in the new LINUX server and imported the WordPress database (I have to admit something went wrong here, so the support guys ended up doing this for me)</li>
<li>my web host provider then pushed the LINUX site live (again, something went wrong here so another phone call was involved in getting them to fix the problem).</li>
<li>Used the plug-in 'Velvet Blues Update URLs' to update all instances of www.mywebsite.com/blog to www.mywebsite.com in posts, links and attachments (i.e. images were not displayed until I did this)</li>
<li>turned on permalinks and checked it worked</li>
</ol>
<p>This was a bit of a palava, but got there in the end. I'm sure there are much easier ways to achieve this, but I'm posting this solution just so non-technical people like myself realise they can call the helpline for their web hosting platform rather than trying to struggle through.</p>
| [
{
"answer_id": 260656,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 0,
"selected": false,
"text": "<p>You need to update all the links in your database as well</p>\n\n<p>You need to use something like <a href=... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115767/"
] | I originally installed wordpress in a subdirectory called /blog. Today I decided to change the URL of my site to remove the /blog element from the URL e.g. from www.mywebsite.com/blog to www.mywebsite.com. Here is what I did:
1. went to settings > general and changed the site address:
WordPress Address (URL): www.mywebsite.com/blog
Site Address (URL): www.mywebsite.com
2. deleted my original homepage (index.html)
3. downloaded the index.php file from the /blog directory, and uploaded a copy into the root directory
4. opened the index.php file from the root directory and changed the following line of code:
require( dirname( **FILE** ) . '/wp-blog-header.php' );
```
require( dirname( __FILE__ ) . '/blog/wp-blog-header.php' );
```
This worked in that I now landed directly on my wordpress blog when I typed in www.mywebsite.com, but all my internal links resulted in 404 errors. So I changed my permalinks to plain (e.g. wwww.mywebsite.com/?p=123), which fixed the broken links. However, I prefer to use the post name structure (e.g. wwww.mywebsite.com/name-of-post) so tried to fix this by doing the following:
5. created a file called .htaccess in the root directory, and typed in the following code:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
This went horribly wrong, resulting in 500 errors that locked my out of the WP dashboard for some time. I can't remember exactly how I fixed this, but the only other change I made was as follows:
6. edited web.config file in /blog directory:
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="WordPress Rule" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>"
```
This still didn't allow post name permalinks, so I set permalinks back to plain. However, I now have a weird situation where about half of my internal links work okay, and the other half result in 404's. I don't really understand how this is possible, as I would have thought it would be all or nothing!
Can anyone please help?
UPDATE - NOW RESOLVED (YAY!):
After struggling to fix this, I contacted the support helpline for the company that provides my web hosting. They said that the fact I was on a windows server was problematic, as it is not really compatible with WordPress. So this is what I / they did:
1. phoned my web host providers and changed to a LINUX server
2. downloaded the free FTP application FileZilla, and imported all of my wordpress files onto my computer. I then transferred them via FTP to the new LINUX server, into the root directory (public\_html).
3. exported my WordPress database from the old windows server and saved onto my computer. I then created a new database in the new LINUX server and imported the WordPress database (I have to admit something went wrong here, so the support guys ended up doing this for me)
4. my web host provider then pushed the LINUX site live (again, something went wrong here so another phone call was involved in getting them to fix the problem).
5. Used the plug-in 'Velvet Blues Update URLs' to update all instances of www.mywebsite.com/blog to www.mywebsite.com in posts, links and attachments (i.e. images were not displayed until I did this)
6. turned on permalinks and checked it worked
This was a bit of a palava, but got there in the end. I'm sure there are much easier ways to achieve this, but I'm posting this solution just so non-technical people like myself realise they can call the helpline for their web hosting platform rather than trying to struggle through. | Please use this query in your Database using PhpMyAdmin
`UPDATE wp_options SET option_value = REPLACE(option_value, 'oldsite.com', 'newsite.com');
UPDATE wp_postmeta SET meta_value = REPLACE(meta_value, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET post_content = REPLACE(post_content, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET post_excerpt = REPLACE(post_excerpt, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET guid = REPLACE(guid, 'oldsite.com', 'newsite.com');`
This will change all your URL's to new ones. |
260,665 | <p>I am working on custom plugin. I need to insert currency names and symbols in table on plugin activation. Right now my database insertion code is :</p>
<pre><code> global $wpdb;
$table_name1 = $wpdb->prefix . "woo_currency";
$curr_name = array('Dollars', 'Ruble', 'Riel');
$curr_symbol = array('$', 'p.', '៛');
$insert = $wpdb->insert($table_name1,
array(
'name' => $curr_name,
'symbol' => $curr_symbol,
),array('%s', '%s'));
</code></pre>
<p>Everthing is working fine except this database insertion on plugin activation. Have you guys any idea. How to do it?</p>
<p>This code gave me error</p>
<blockquote>
<p>The plugin generated 416 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.</p>
</blockquote>
<p>I want to add <a href="http://blog.smarttutorials.net/2017/01/List-Of-Country-Names-with-Currency-Symbol-SQL-Query-For-MySQL.html" rel="nofollow noreferrer">Currencies name & symbols</a> these all.</p>
| [
{
"answer_id": 260656,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 0,
"selected": false,
"text": "<p>You need to update all the links in your database as well</p>\n\n<p>You need to use something like <a href=... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88892/"
] | I am working on custom plugin. I need to insert currency names and symbols in table on plugin activation. Right now my database insertion code is :
```
global $wpdb;
$table_name1 = $wpdb->prefix . "woo_currency";
$curr_name = array('Dollars', 'Ruble', 'Riel');
$curr_symbol = array('$', 'p.', '៛');
$insert = $wpdb->insert($table_name1,
array(
'name' => $curr_name,
'symbol' => $curr_symbol,
),array('%s', '%s'));
```
Everthing is working fine except this database insertion on plugin activation. Have you guys any idea. How to do it?
This code gave me error
>
> The plugin generated 416 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
>
>
>
I want to add [Currencies name & symbols](http://blog.smarttutorials.net/2017/01/List-Of-Country-Names-with-Currency-Symbol-SQL-Query-For-MySQL.html) these all. | Please use this query in your Database using PhpMyAdmin
`UPDATE wp_options SET option_value = REPLACE(option_value, 'oldsite.com', 'newsite.com');
UPDATE wp_postmeta SET meta_value = REPLACE(meta_value, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET post_content = REPLACE(post_content, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET post_excerpt = REPLACE(post_excerpt, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET guid = REPLACE(guid, 'oldsite.com', 'newsite.com');`
This will change all your URL's to new ones. |
260,669 | <p>I would like to limit the +New admin menu to only show the single sub menu Event ("Veranstaltung").
Basically the users are allowed to create other items as well but not from that +New menu. </p>
<p><a href="https://i.stack.imgur.com/mNFRB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mNFRB.png" alt="+New Admin Menu"></a></p>
<p>I already tried it with "Adminimize" plugin as this can remove the other items but it will leave the new media link intact once you click directly "+New". </p>
<p><a href="https://i.stack.imgur.com/DENRg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DENRg.png" alt="+New Admin Menu - link still there"></a></p>
<p>I already added some other logic to remove items from the left admin menu like:</p>
<pre><code>function remove_menus() {
remove_menu_page('edit.php?post_type=mdocs-posts');
}
add_action('admin_menu', 'remove_menus');
</code></pre>
<p>But I can't get how to modify the +New. Any hints? </p>
<p>Thank you!</p>
| [
{
"answer_id": 260671,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 4,
"selected": true,
"text": "<p><strong>To hide everything (menu and submenu)-</strong></p>\n\n<pre><code>function wpse_260669_remove_new_cont... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260669",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115781/"
] | I would like to limit the +New admin menu to only show the single sub menu Event ("Veranstaltung").
Basically the users are allowed to create other items as well but not from that +New menu.
[](https://i.stack.imgur.com/mNFRB.png)
I already tried it with "Adminimize" plugin as this can remove the other items but it will leave the new media link intact once you click directly "+New".
[](https://i.stack.imgur.com/DENRg.png)
I already added some other logic to remove items from the left admin menu like:
```
function remove_menus() {
remove_menu_page('edit.php?post_type=mdocs-posts');
}
add_action('admin_menu', 'remove_menus');
```
But I can't get how to modify the +New. Any hints?
Thank you! | **To hide everything (menu and submenu)-**
```
function wpse_260669_remove_new_content(){
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'new-content' );
}
add_action( 'wp_before_admin_bar_render', 'wpse_260669_remove_new_content' );
```
**To hide specific menu/submenu item(s)-**
```
function wpse_260669_remove_new_content_items(){
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'new-post' ); // hides post CPT
$wp_admin_bar->remove_menu( 'new-product' ); // hides product CPT
$wp_admin_bar->remove_menu( 'new-page' ); // hides page CPT
$wp_admin_bar->remove_menu( 'new-media' ); // hides media
}
add_action( 'wp_before_admin_bar_render', 'wpse_260669_remove_new_content_items' );
```
**So, the basic rule is-**
```
function your_boo_bar_function() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'your-unique-menu-id' );
}
add_action( 'wp_before_admin_bar_render', 'your_boo_bar_function' );
```
**Add a new menu-**
```
function wpse_260669_add_menu(){
global $wp_admin_bar;
$wp_admin_bar->add_node(
array(
'id' => 'google-menu',
'title' => 'Google',
'href' => 'http://google.com',
'parent' => 'new-content', // so, it'll be set as a child of 'new-content'. remove this to use this as a parent menu
'meta' => array( 'class' => 'my-custom-class' ),
)
);
}
add_action( 'wp_before_admin_bar_render', 'wpse_260669_add_menu' );
```
**Update an existing menu-**
If you want to update an existing menu item, just add a new item using the ID of your desired menu.
To update +New ('content-new'), use this code-
```
function wpse_260669_update_menu(){
global $wp_admin_bar;
$wp_admin_bar->add_node(
array(
'id' => 'new-content', // id of an existing menu
'href' => 'your_new_url_goes_here', // set new URL
)
);
}
add_action( 'wp_before_admin_bar_render', 'wpse_260669_update_menu' );
```
**How to get menu ID-**
The easiest way is to inspect element with Firebug and take the ID. See this screenshot-
[](https://i.stack.imgur.com/X4DMA.jpg)
Navigate to your desired menu item and get the string next to `wp-admin-bar-` |
260,678 | <p>I have "Color Filters for WooCommerce" plugin and "color" taxonomy.</p>
<p>Each taxonomy have one custom field - color picker.</p>
<p>I want to display on archive page current color picker value of each product's.</p>
<p>I can call </p>
<pre><code>get_option( 'nm_taxonomy_colors' );
</code></pre>
<p>And I'll get all values from this field, but I need only current.</p>
<p>This plugin have <a href="https://www.elementous.com/documentation/color-filters-for-woocommerce/modifications-and-development/" rel="nofollow noreferrer">doc</a>, but I don't know how I can use this filters</p>
<pre><code>elm_cf_get_terms_args
elm_cf_color_style_attribute
</code></pre>
| [
{
"answer_id": 260711,
"author": "1naveengiri",
"author_id": 114894,
"author_profile": "https://wordpress.stackexchange.com/users/114894",
"pm_score": 0,
"selected": false,
"text": "<p>you can use it like this.</p>\n\n<pre><code>$saved_colors = get_option( 'nm_taxonomy_colors' );\n//just... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98449/"
] | I have "Color Filters for WooCommerce" plugin and "color" taxonomy.
Each taxonomy have one custom field - color picker.
I want to display on archive page current color picker value of each product's.
I can call
```
get_option( 'nm_taxonomy_colors' );
```
And I'll get all values from this field, but I need only current.
This plugin have [doc](https://www.elementous.com/documentation/color-filters-for-woocommerce/modifications-and-development/), but I don't know how I can use this filters
```
elm_cf_get_terms_args
elm_cf_color_style_attribute
``` | The author of plugin help me with that. Thanks all.
```
global $post;
$product_colors = get_the_terms( $post, 'product_color' );
$saved_colors = get_option( 'nm_taxonomy_colors' );
if(isset($product_colors) && is_array($product_colors)){
foreach($product_colors as $color){
$term_id = $color->term_id;
$hex_code = $saved_colors[$term_id];
echo $hex_code . '<br />';
}
}
``` |
260,682 | <p>Hi I am using a Ubuntu system. I am using a shell script to download wordpress from wget, update config and run it from nginx server. </p>
<p>Now I want to update this shell script so that when we install a fresh copy of WordPress, I get some plugins pre-installed.
So I installed wp-cli and ran the command</p>
<pre><code>wp plugin install w3-total-cache --activate --allow-root
</code></pre>
<p>This command says the plugin has been activated successfully. But when I go to the site URL in the plugins section, it gives the following error</p>
<p><code>The plugin w3-total-cache/w3-total-cache.php has been deactivated due to an error: Plugin file does not exist.</code></p>
<p>This is true for any plugin that I try to install.</p>
<p>When I go to the plugins folder inside wp-content, I can see that plugin files exist. But still I get the error. </p>
<p>How to resolve this. Please help </p>
| [
{
"answer_id": 260691,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Caching plugins usually require some additional manual work in moving some files from the plugin director... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115798/"
] | Hi I am using a Ubuntu system. I am using a shell script to download wordpress from wget, update config and run it from nginx server.
Now I want to update this shell script so that when we install a fresh copy of WordPress, I get some plugins pre-installed.
So I installed wp-cli and ran the command
```
wp plugin install w3-total-cache --activate --allow-root
```
This command says the plugin has been activated successfully. But when I go to the site URL in the plugins section, it gives the following error
`The plugin w3-total-cache/w3-total-cache.php has been deactivated due to an error: Plugin file does not exist.`
This is true for any plugin that I try to install.
When I go to the plugins folder inside wp-content, I can see that plugin files exist. But still I get the error.
How to resolve this. Please help | Caching plugins usually require some additional manual work in moving some files from the plugin directory to the root of the `wp-content` directory and maybe some `wp-config.php` changes. It is possible that the plugin fails to initialize due to that. |
260,701 | <p>In my theme, jQuery is loaded in the header by default. I even dequed it in my <code>functions.php</code> but still in the header I have the jquery : </p>
<pre><code>function remove_jquery_migrate( &$scripts){
if(!is_admin()){
$scripts->remove( 'jquery');
$scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1' );
}
}
add_filter( 'wp_default_scripts', 'remove_jquery_migrate' );
function wpdocs_dequeue_script() {
wp_dequeue_script( 'jquery' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
</code></pre>
<p>but this is printed in the header: </p>
<pre><code><script type='text/javascript' src='...wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
</code></pre>
<p>I don't know if a plugin is causing this but I want to remove this as I am already loading the jquery using Google CDN in the footer. </p>
| [
{
"answer_id": 260704,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 2,
"selected": true,
"text": "<p>An example on how to deregister a WordPress built-in library and load your own:</p>\n\n<pre><code>function load_... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260701",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115810/"
] | In my theme, jQuery is loaded in the header by default. I even dequed it in my `functions.php` but still in the header I have the jquery :
```
function remove_jquery_migrate( &$scripts){
if(!is_admin()){
$scripts->remove( 'jquery');
$scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1' );
}
}
add_filter( 'wp_default_scripts', 'remove_jquery_migrate' );
function wpdocs_dequeue_script() {
wp_dequeue_script( 'jquery' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
```
but this is printed in the header:
```
<script type='text/javascript' src='...wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
```
I don't know if a plugin is causing this but I want to remove this as I am already loading the jquery using Google CDN in the footer. | An example on how to deregister a WordPress built-in library and load your own:
```
function load_custom_scripts() {
wp_deregister_script( 'jquery' );
wp_register_script('jquery', '//code.jquery.com/jquery-2.2.4.min.js', array(), '2.2.4', true); // true will place script in the footer
wp_enqueue_script( 'jquery' );
}
if(!is_admin()) {
add_action('wp_enqueue_scripts', 'load_custom_scripts', 99);
}
``` |
260,713 | <p>Working on a site that has a lot of posts, I need to display 3 posts from a particular category, but all of them need to be from the latest 10 published on the site. I can either grab 3 completely random posts (which tends to pull posts that are very old) or grab 10 posts (but I don't know how to then randomize the order and only display 3).</p>
<p>So far, I have this query:</p>
<pre><code>$args = array(
'post_type' => 'post',
'category_name' => 'mycategory',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC',
'meta_key' => '_thumbnail_id',
'no_found_rows' => 'true'
);
$query = new WP_Query( $args );
</code></pre>
<p>along with this attempt to get 3 random posts from the 10 queried:</p>
<pre><code>$randomPosts = shuffle( $query );
$randomPosts = array_slice( $randomPosts, 0, 3 );
</code></pre>
<p>But treating the results as an array doesn't work, since it's actually an object.<br />
My only other thought is to use <code>'posts_per_page' = 3</code> with <code>'orderby' => 'rand'</code> to grab 3 random posts and add a <code>'date_query'</code> to restrict it to the past 6 months. That would be close, but it would be preferable to restrict the query to the 10 most recent posts (they may all be published 3 days ago or 5 months ago, they are published together in uneven spurts).</p>
<p>What is the best approach?<br />
Query the 10 latest posts as I'm doing, then convert the object to an array, shuffle, and slice, and convert it back to an object, or is there a simpler, more efficient way to accomplish the goal?</p>
| [
{
"answer_id": 260720,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>There's one way with:</p>\n\n<pre><code>$args = [\n 'post_type' => 'post',\n 'posts_per_p... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260713",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102815/"
] | Working on a site that has a lot of posts, I need to display 3 posts from a particular category, but all of them need to be from the latest 10 published on the site. I can either grab 3 completely random posts (which tends to pull posts that are very old) or grab 10 posts (but I don't know how to then randomize the order and only display 3).
So far, I have this query:
```
$args = array(
'post_type' => 'post',
'category_name' => 'mycategory',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC',
'meta_key' => '_thumbnail_id',
'no_found_rows' => 'true'
);
$query = new WP_Query( $args );
```
along with this attempt to get 3 random posts from the 10 queried:
```
$randomPosts = shuffle( $query );
$randomPosts = array_slice( $randomPosts, 0, 3 );
```
But treating the results as an array doesn't work, since it's actually an object.
My only other thought is to use `'posts_per_page' = 3` with `'orderby' => 'rand'` to grab 3 random posts and add a `'date_query'` to restrict it to the past 6 months. That would be close, but it would be preferable to restrict the query to the 10 most recent posts (they may all be published 3 days ago or 5 months ago, they are published together in uneven spurts).
What is the best approach?
Query the 10 latest posts as I'm doing, then convert the object to an array, shuffle, and slice, and convert it back to an object, or is there a simpler, more efficient way to accomplish the goal? | There's one way with:
```
$args = [
'post_type' => 'post',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC',
'no_found_rows' => 'true',
'_shuffle_and_pick' => 3 // <-- our custom argument
];
$query = new \WP_Query( $args );
```
where the custom `_shuffle_and_pick` attribute is supported by this demo plugin:
```
<?php
/**
* Plugin Name: Support for the _shuffle_and_pick WP_Query argument.
*/
add_filter( 'the_posts', function( $posts, \WP_Query $query )
{
if( $pick = $query->get( '_shuffle_and_pick' ) )
{
shuffle( $posts );
$posts = array_slice( $posts, 0, (int) $pick );
}
return $posts;
}, 10, 2 );
``` |
260,739 | <pre><code>$args = array(
//'post_type' => 'article',
'posts_per_page' => 5,
'category' => 'starter',
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query($args);
while($query->have_posts()){
the_content();
}
</code></pre>
| [
{
"answer_id": 260742,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 1,
"selected": false,
"text": "<p>Your question is <strong>very</strong> unclear (given that you don't actually ask a quest... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260739",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115834/"
] | ```
$args = array(
//'post_type' => 'article',
'posts_per_page' => 5,
'category' => 'starter',
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query($args);
while($query->have_posts()){
the_content();
}
``` | Your question is **very** unclear (given that you don't actually ask a question), but there are 2 problems with your code, both of which are corrected below:
```
$args = array (
//'post_type' => 'article',
'posts_per_page' => 5,
'category_name' => 'starter', // changed from 'category' to 'category_name'
'meta_query' => array (
array (
'key' => 'recommended_article',
'value' => '1',
'compare' => '=', // changed from '==' to '='
),
),
) ;
$query = new WP_Query ($args) ;
while ($query->have_posts ()) {
the_content () ;
}
```
For the details of *why* these changes are necessary, see [WP\_Query, Category Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters) and [WP\_Query, Custom Field Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters). |
260,756 | <p>Does anyone know how I would automatically add <code><div class="table-responsive"></code> before every instance of a <code><table></code> on a WordPress site using filter referencing? I would also need to add a <code></div></code> to every instance of <code></table></code> as well.</p>
| [
{
"answer_id": 260758,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>You can filter <code>the_content</code> and use <code>preg_replace()</code> to look for instances of... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260756",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94729/"
] | Does anyone know how I would automatically add `<div class="table-responsive">` before every instance of a `<table>` on a WordPress site using filter referencing? I would also need to add a `</div>` to every instance of `</table>` as well. | You can filter `the_content` and use `preg_replace()` to look for instances of `<table></table>` and then surround them with your `<div>`.
```
add_action( 'the_content', 'wpse_260756_the_content', 10, 1 );
function wpse_260756_the_content( $content ) {
$pattern = "/<table(.*?)>(.*?)<\/table>/i";
$replacement = '<div class="table-responsive"><table$1>$2</table></div>';
return preg_replace( $pattern, $replacement, $content );
}
``` |
260,773 | <p>I'm inexperienced with ajax. I'm building a form that will allow the user to grab a custom post type from the first field that will return the value of the post ID. Then, I'd like ajax to take that post ID and build a second dropdown based on some custom fields for that post. </p>
<p>Here's what I have so far, which was adapted from the first answer on this question: <a href="https://wordpress.stackexchange.com/questions/177141/filter-a-second-dropdown-list-when-a-value-is-chosen-in-the-first-one">Filter a second dropdown list when a value is chosen in the first one</a></p>
<p>In functions.php:</p>
<pre><code>if ( is_admin() ) {
add_action( 'wp_ajax_dynamic_dropdown', 'dynamic_dropdown_func' );
add_action( 'wp_ajax_nopriv_dynamic_dropdown', 'dynamic_dropdown_func' );
}
function dynamic_dropdown_func () {
global $wpdb;
if (isset($_POST['event'])) {
$event_id = $_POST['event'];
$first = get_field('first_day',$event_id);
$last = get_field('last_day',$event_id);
$event_dates = '<option value="" disabled selected>Choose Date</option>';
$event_dates .= '<option value="'.$first.'">'.$first.'</option>';
while($first<$last) :
$first = $first + 1;
$event_dates .= '<option value="'.$first.'">'.$first.'</option>';
endwhile;
}
ob_clean();
return $event_dates;
wp_die();
}
</code></pre>
<p>(I'm aware the code to build the dates still needs some work to display proper dates.)</p>
<p>And then, in the page template:</p>
<pre><code><?php function date_chooser () {
$ajax_url = admin_url( 'admin-ajax.php' );
$grabDates = "
<script>
var ajaxUrl = '{$ajax_url}',
dropdownEvent = jQuery('#chooseEvent'),
dropdownDate = jQuery('#chooseDate');
dropdownEvent.on('change', function (e) {
var value = e.target.selectedOptions[0].value,
success,
data;
if (!!value) {
data = {
'event' : value,
'action' : 'dynamic_dropdown'
};
success = function ( response ) {
dropdownDate.html( response );
};
jQuery.post( ajaxUrl, data, success );
}
});
</script>";
return $grabDates;
}
echo date_chooser(); ?>
</code></pre>
<p>This code is getting me part of the way. Once the #chooseEvent dropdown has a selection, it is capture the proper post ID, and then the #chooseDate dropdown just empties itself from my placeholder but never loads anything else. </p>
<p>I've tried just having the dynamic_dropdown_func() just return a "Hello world!" and it doesn't do that either, so somehow I think I'm not triggering and returning the ajax function properly.</p>
| [
{
"answer_id": 261162,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 3,
"selected": true,
"text": "<p>In <code>dynamic_dropdown_func()</code>, at the end try <code>echo $event_dates;</code> instead of <code>return ... | 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260773",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2041/"
] | I'm inexperienced with ajax. I'm building a form that will allow the user to grab a custom post type from the first field that will return the value of the post ID. Then, I'd like ajax to take that post ID and build a second dropdown based on some custom fields for that post.
Here's what I have so far, which was adapted from the first answer on this question: [Filter a second dropdown list when a value is chosen in the first one](https://wordpress.stackexchange.com/questions/177141/filter-a-second-dropdown-list-when-a-value-is-chosen-in-the-first-one)
In functions.php:
```
if ( is_admin() ) {
add_action( 'wp_ajax_dynamic_dropdown', 'dynamic_dropdown_func' );
add_action( 'wp_ajax_nopriv_dynamic_dropdown', 'dynamic_dropdown_func' );
}
function dynamic_dropdown_func () {
global $wpdb;
if (isset($_POST['event'])) {
$event_id = $_POST['event'];
$first = get_field('first_day',$event_id);
$last = get_field('last_day',$event_id);
$event_dates = '<option value="" disabled selected>Choose Date</option>';
$event_dates .= '<option value="'.$first.'">'.$first.'</option>';
while($first<$last) :
$first = $first + 1;
$event_dates .= '<option value="'.$first.'">'.$first.'</option>';
endwhile;
}
ob_clean();
return $event_dates;
wp_die();
}
```
(I'm aware the code to build the dates still needs some work to display proper dates.)
And then, in the page template:
```
<?php function date_chooser () {
$ajax_url = admin_url( 'admin-ajax.php' );
$grabDates = "
<script>
var ajaxUrl = '{$ajax_url}',
dropdownEvent = jQuery('#chooseEvent'),
dropdownDate = jQuery('#chooseDate');
dropdownEvent.on('change', function (e) {
var value = e.target.selectedOptions[0].value,
success,
data;
if (!!value) {
data = {
'event' : value,
'action' : 'dynamic_dropdown'
};
success = function ( response ) {
dropdownDate.html( response );
};
jQuery.post( ajaxUrl, data, success );
}
});
</script>";
return $grabDates;
}
echo date_chooser(); ?>
```
This code is getting me part of the way. Once the #chooseEvent dropdown has a selection, it is capture the proper post ID, and then the #chooseDate dropdown just empties itself from my placeholder but never loads anything else.
I've tried just having the dynamic\_dropdown\_func() just return a "Hello world!" and it doesn't do that either, so somehow I think I'm not triggering and returning the ajax function properly. | In `dynamic_dropdown_func()`, at the end try `echo $event_dates;` instead of `return $event_dates;`.
Also, I'm wondering why you declare `global $wpdb;` when you don't seem to use it? |
260,789 | <p>So i'm adding a script into my site via <code>functions.php</code> that lives in the plugins directory. The code is pretty straightforward:</p>
<pre><code>function add_jq_script() {
wp_register_script('r_footer', plugins_url('/responsiveFooter.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('r_footer');
}
add_action( 'wp_enqueue_scripts', 'add_jq_script', 999 );
</code></pre>
<p>the plugins seem to be working on local site, but in dev console, i'm getting a 404 that seems to be concatting my site-url and the absolute url for my plugins:
<code>http://localhost/~thisuser/wordpress/wp-content/plugins/Users/thisuser/Sites/wordpress/wp-content/themes/liberty/responsiveFooter.js?ver=1.1</code></p>
<p>i'm a bit new to wordpress, the url should be <code>http://localhost/~thisuser/wordpress/wp-content/plugins/responsiveFooter.js</code></p>
<p>is there some wp-option i need to change or some plugin setting somewhere to fix this?</p>
| [
{
"answer_id": 260790,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 0,
"selected": false,
"text": "<p>You have used wrong callable function in <code>add_action()</code>. Your code should be something like this-<... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260789",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106975/"
] | So i'm adding a script into my site via `functions.php` that lives in the plugins directory. The code is pretty straightforward:
```
function add_jq_script() {
wp_register_script('r_footer', plugins_url('/responsiveFooter.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('r_footer');
}
add_action( 'wp_enqueue_scripts', 'add_jq_script', 999 );
```
the plugins seem to be working on local site, but in dev console, i'm getting a 404 that seems to be concatting my site-url and the absolute url for my plugins:
`http://localhost/~thisuser/wordpress/wp-content/plugins/Users/thisuser/Sites/wordpress/wp-content/themes/liberty/responsiveFooter.js?ver=1.1`
i'm a bit new to wordpress, the url should be `http://localhost/~thisuser/wordpress/wp-content/plugins/responsiveFooter.js`
is there some wp-option i need to change or some plugin setting somewhere to fix this? | `plugins_url` will output the absolute file path of the plugins directory in your WordPress install.
This of course won't work for a client (browser) calling a script.
To access scripts from the plugins directory, you'll want to use `plugin_dir_url()` which will get you the url of the plugin directory.
**Some things to note about `plugin_dir_url()`**
* You need to specify the directory of the plugin name your script is located
* The function output contains a trailing slash, so you won't need to concatenate a slash.
Lets say your plugin is called "my\_plugin" and the script is located in a "js" directory, your script registration would look something like this:
```
wp_register_script('r_footer', plugins_dir_url() . 'my_plugin/js/responsiveFooter.js', array('jquery'),'1.1', true);
```
Note the omission of `__FILE__` which will output the absolute path of the current file (not what you want).
---
If your script is in your active theme, you'll want to use a different function: `get_stylesheet_directory_uri`
**Some things to note about `get_stylesheet_directory_uri`**
* It requires a trailing slash unlike `plugin_dir_url()`
* You will need to specify the directory path in the theme where your script is located.
* This function works especially well if you are working with child themes, but a child theme is not required. If you are working with a child theme, this function will get the path to the style.css file in your child theme rather than the parent theme.
* Note that the function is ur**i** NOT ur**l**
So lets say your theme is called "my\_theme" and the javascript is located in a "js" file, your registration script would look something like this:
```
wp_register_script('r_footer', get_stylesheet_directory_uri() . '/my_theme/js/responsiveFooter.js', array('jquery'),'1.1', true);
```
---
**Links to documentation:**
* plugin\_dir\_url - <https://codex.wordpress.org/Function_Reference/plugin_dir_url>
* get\_stylesheet\_uri - <https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri>
* get\_template\_directory\_uri (which is an alternative function to get\_stylesheet\_uri, but isn't advised for child themes) - <https://developer.wordpress.org/reference/functions/get_template_directory_uri/>
* plugins\_url - <https://codex.wordpress.org/Function_Reference/plugins_url> |
260,800 | <p>I want to save my form data via jquery but i can't able to access it in my script.Can anyone help me.
URL access in script: <strong>url: 'admin.php?page=insert.php',</strong></p>
<p>My script</p>
<pre><code>$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var schema_key = $("#schema_key").val();
$.ajax({
type: 'post',
url: 'admin.php?page=insert.php',
data: schema_key,
success: function () {
alert('form was submitted');
}
});
});
});
</code></pre>
| [
{
"answer_id": 260793,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>Prefixes are used to avoid conflicts. If your framework is used to build a theme, the chances are high that there isn'... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260800",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114992/"
] | I want to save my form data via jquery but i can't able to access it in my script.Can anyone help me.
URL access in script: **url: 'admin.php?page=insert.php',**
My script
```
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var schema_key = $("#schema_key").val();
$.ajax({
type: 'post',
url: 'admin.php?page=insert.php',
data: schema_key,
success: function () {
alert('form was submitted');
}
});
});
});
``` | Prefixes are used to avoid conflicts. If your framework is used to build a theme, the chances are high that there isn't a second theme framework in use at the same time. So there is no conflict, and therefore no need for a prefix.
The exception are CSS classes generated by the WordPress core, for example in the comment form. If you are using the same class names for an entirely different purpose, you need a prefix, or better class names for your use case. |
260,813 | <p>I'm working to optimize a site that I've recently taken management of, and it appears to me that there are a fair few unused templates. I want to remove all the unused and redundant template files so that we can focus our developments on those templates we do support, however there are 100+ pages and posts on this site, so I can't just do a spot check, I need a robust query.</p>
<p>I've established how to query which page template is being called from joining wp_posts and wp_postmeta, and I've sussed out which post formats are being used by querying wp_posts and wp_terms via wp_term_relationships BUT... this still doesn't seem to tell me whether the index.php is ever used (and I don't think it is).</p>
<p>I'm probably missing something obvious, but is there a way to see which of the normal Wordpress theme files are actually being called? OR is it that I have all the information already and 'index.php' just isn't being used. </p>
<p>Any help would be much appreciated!</p>
<p>Thanks</p>
| [
{
"answer_id": 260836,
"author": "Netanel Perez",
"author_id": 114386,
"author_profile": "https://wordpress.stackexchange.com/users/114386",
"pm_score": -1,
"selected": false,
"text": "<p>You mean something like this?</p>\n\n<pre><code>$args = array(\n 'meta_key' => '_wp_page_templ... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260813",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115867/"
] | I'm working to optimize a site that I've recently taken management of, and it appears to me that there are a fair few unused templates. I want to remove all the unused and redundant template files so that we can focus our developments on those templates we do support, however there are 100+ pages and posts on this site, so I can't just do a spot check, I need a robust query.
I've established how to query which page template is being called from joining wp\_posts and wp\_postmeta, and I've sussed out which post formats are being used by querying wp\_posts and wp\_terms via wp\_term\_relationships BUT... this still doesn't seem to tell me whether the index.php is ever used (and I don't think it is).
I'm probably missing something obvious, but is there a way to see which of the normal Wordpress theme files are actually being called? OR is it that I have all the information already and 'index.php' just isn't being used.
Any help would be much appreciated!
Thanks | Here's a rough function I use to handle this, it should work well for anyone out there wanting to do this quick and easy. Add this this your functions.php file and then visit your site with `?template_report` added onto the URL to display a report for every custom theme template.
**It's rough, I'd suggest commenting/uncommenting the `add_action` call when you want to use it.**
```
/**
* Theme Template Usage Report
*
* Displays a data dump to show you the pages in your WordPress
* site that are using custom theme templates.
*/
function theme_template_usage_report( $file = false ) {
if ( ! isset( $_GET['template_report'] ) ) return;
$templates = wp_get_theme()->get_page_templates();
$report = array();
echo '<h1>Page Template Usage Report</h1>';
echo "<p>This report will show you any pages in your WordPress site that are using one of your theme's custom templates.</p>";
foreach ( $templates as $file => $name ) {
$q = new WP_Query( array(
'post_type' => 'page',
'posts_per_page' => -1,
'meta_query' => array( array(
'key' => '_wp_page_template',
'value' => $file
) )
) );
$page_count = sizeof( $q->posts );
if ( $page_count > 0 ) {
echo '<p style="color:green">' . $file . ': <strong>' . sizeof( $q->posts ) . '</strong> pages are using this template:</p>';
echo "<ul>";
foreach ( $q->posts as $p ) {
echo '<li><a href="' . get_permalink( $p, false ) . '">' . $p->post_title . '</a></li>';
}
echo "</ul>";
} else {
echo '<p style="color:red">' . $file . ': <strong>0</strong> pages are using this template, you should be able to safely delete it from your theme.</p>';
}
foreach ( $q->posts as $p ) {
$report[$file][$p->ID] = $p->post_title;
}
}
exit;
}
add_action( 'wp', 'theme_template_usage_report' );
```
The output looks like this:
[](https://i.stack.imgur.com/ezZdv.png) |
260,826 | <p>Say I have a user meta field that is called "meta1".
I want to get posts (via get_posts or the like) who's author meta1 = true.
Any idea how I should approach this?</p>
| [
{
"answer_id": 260832,
"author": "Netanel Perez",
"author_id": 114386,
"author_profile": "https://wordpress.stackexchange.com/users/114386",
"pm_score": 0,
"selected": false,
"text": "<p>You can define it in the loop's arguments and i believe it will work with other WP functions as well<... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115876/"
] | Say I have a user meta field that is called "meta1".
I want to get posts (via get\_posts or the like) who's author meta1 = true.
Any idea how I should approach this? | Get for all users / authors with user meta field. `meta1 = true`
```
$args = array(
'meta_key' => 'meta1',
'meta_value' => 'true',
'meta_compare' => '=',
'fields' => 'all',
);
$users = get_users( $args );
```
Store user id and login into an array `authors`
```
$authors = array();
foreach ( (array) $users as $user ) {
authors[ $user->ID ] = $user->user_login;
}
```
Now you can pass authors in your posts query.
```
$posts = query_posts( array( 'author__in'=> array_keys( $authors ) ) );
```
**Or**
```
$posts = new WP_Query( array( 'author__in' => array( array_keys( $authors ) ) );
```
Final code
```
$args = array(
'meta_key' => 'meta1',
'meta_value' => 'true',
'meta_compare' => '=',
'fields' => 'all',
);
$users = get_users( $args );
$authors = array();
foreach ( (array) $users as $user ) {
$authors[ $user->ID ] = $user->user_login;
}
$query = new WP_Query( array( 'author__in' => array( array_keys( $authors ) ) );
if ( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();
//print post contents, title etc
endwhile;
endif;
wp_reset_postdata();
``` |
260,828 | <p>I've built a membership site where users can post listings from the frontend, edit those, and ideally also delete them.</p>
<p>For the latter, I'd like to echo a "delete post" link to the frontend. The problem is that <code>get_delete_post_link()</code>.</p>
<p>So from this:
<code>
$theID = get_the_ID(); // inside loop
echo $theID;
<a href="<?php echo get_delete_post_link( $theID, '', false ); ?> ">Delete This Post</a>
</code></p>
<p>I get:
<code>
123 /* = $theID; */
<a href="_">Delete This Post</a>
</code></p>
<p>I tried the following things:</p>
<ul>
<li>passing only $theID as argument instead of the full three</li>
<li>passing <code>$theID, '', true</code></li>
<li>ran checks as described in the answers here: <a href="https://wordpress.stackexchange.com/questions/99344/cant-echo-get-delete-post-link">Can't echo get_delete_post_link</a></li>
<li>the problem occurs both when I'm logged in as admin and as normal user (with added capacities)</li>
<li>I made sure the permissions for the custom post type are mapped correctly</li>
<li>outside the loop it works, but not inside the loop (the codex says it can be done within the loop: <a href="https://codex.wordpress.org/Function_Reference/get_delete_post_link" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/get_delete_post_link</a>).</li>
</ul>
<p>Here's the loop I'm using:</p>
<pre><code> // arguments
$arguments = array(
'post_type' => 'CustomType',
'posts_per_page' => -1,
'author_name' => $current_user->user_login
);
// query
$the_query = new WP_Query($arguments);
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if( has_term( 'custom_term', 'custom_taxonomy' ) ): ?>
/* stuff happens here */
/* get_delete_post_link() returns nothing */
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
</code></pre>
<p>I'm at the end of my wits with this, any help would be appreciated.</p>
| [
{
"answer_id": 260830,
"author": "Netanel Perez",
"author_id": 114386,
"author_profile": "https://wordpress.stackexchange.com/users/114386",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><p>get_delete_post_link() Should work without parameters if you are using it inside the loop</... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104550/"
] | I've built a membership site where users can post listings from the frontend, edit those, and ideally also delete them.
For the latter, I'd like to echo a "delete post" link to the frontend. The problem is that `get_delete_post_link()`.
So from this:
`$theID = get_the_ID(); // inside loop
echo $theID;
<a href="<?php echo get_delete_post_link( $theID, '', false ); ?> ">Delete This Post</a>`
I get:
`123 /* = $theID; */
<a href="_">Delete This Post</a>`
I tried the following things:
* passing only $theID as argument instead of the full three
* passing `$theID, '', true`
* ran checks as described in the answers here: [Can't echo get\_delete\_post\_link](https://wordpress.stackexchange.com/questions/99344/cant-echo-get-delete-post-link)
* the problem occurs both when I'm logged in as admin and as normal user (with added capacities)
* I made sure the permissions for the custom post type are mapped correctly
* outside the loop it works, but not inside the loop (the codex says it can be done within the loop: <https://codex.wordpress.org/Function_Reference/get_delete_post_link>).
Here's the loop I'm using:
```
// arguments
$arguments = array(
'post_type' => 'CustomType',
'posts_per_page' => -1,
'author_name' => $current_user->user_login
);
// query
$the_query = new WP_Query($arguments);
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if( has_term( 'custom_term', 'custom_taxonomy' ) ): ?>
/* stuff happens here */
/* get_delete_post_link() returns nothing */
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
```
I'm at the end of my wits with this, any help would be appreciated. | 1. get\_delete\_post\_link() Should work without parameters if you are using it inside the loop
2. I believe that you need to remove your wp\_reset\_query() that is placed before the if( $the\_query->have\_posts().. |
260,850 | <p>I would like to list out the child terms related to the taxonomy archive and then list posts belonging to the child terms below the term name.</p>
<p>I currently have the following code which successfully lists out the child terms.</p>
<pre><code>$this_term = get_queried_object();
$args = array(
'parent' => $this_term->term_id,
'orderby' => 'slug',
'hide_empty' => false
);
$child_terms = get_terms( $this_term->taxonomy, $args );
echo '<ul>';
foreach ($child_terms as $term) {
//List the child topics
echo '<li><h3><a href="' . get_term_link( $term->name, $this_term->taxonomy ) . '">' . $term->name . '</h3></a></li>';
// Try to list the contained posts (DOES NOT WORK)
?> <div><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><div><?php
}//end foreach
echo '</ul>';
</code></pre>
<p>However, I need it to then display the permalinks for articles that belong to that child term. My current method of using 'the_permalink' just returns the same post in each topic.</p>
<p>Can anyone point me in the right direction?</p>
| [
{
"answer_id": 260858,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>You need another query that will find the posts associated with each child term, the post-containing <cod... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83253/"
] | I would like to list out the child terms related to the taxonomy archive and then list posts belonging to the child terms below the term name.
I currently have the following code which successfully lists out the child terms.
```
$this_term = get_queried_object();
$args = array(
'parent' => $this_term->term_id,
'orderby' => 'slug',
'hide_empty' => false
);
$child_terms = get_terms( $this_term->taxonomy, $args );
echo '<ul>';
foreach ($child_terms as $term) {
//List the child topics
echo '<li><h3><a href="' . get_term_link( $term->name, $this_term->taxonomy ) . '">' . $term->name . '</h3></a></li>';
// Try to list the contained posts (DOES NOT WORK)
?> <div><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><div><?php
}//end foreach
echo '</ul>';
```
However, I need it to then display the permalinks for articles that belong to that child term. My current method of using 'the\_permalink' just returns the same post in each topic.
Can anyone point me in the right direction? | I was able to get this working with the following code. I used the relation operator AND, referenced the var ($this\_term) that contained get\_queried\_object(); to set the taxonomy in the tax\_query and adjusted the term field in the tax\_query.
```
$this_term = get_queried_object();
$args = array(
'parent' => $this_term->term_id,
'orderby' => 'slug',
'hide_empty' => false
);
$child_terms = get_terms( $this_term->taxonomy, $args );
echo '<ul>';
foreach ($child_terms as $term) {
// List the child topic
echo '<li><h3><a href="' . get_term_link( $term->name, $this_term->taxonomy ) . '">' . $term->name . '</a></h3>';
// Get posts from that child topic
$query = new WP_Query( array(
'post_type' => 'kb',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => $this_term->taxonomy,
'field' => 'slug',
'terms' => array( $term->slug )
)
)
) );
// List the posts
if($query->have_posts()) {
while($query->have_posts()) : $query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li><?php
endwhile;
} else { echo "no posts";}
// close our <li>
echo '</li>';
} //end foreach
``` |
260,854 | <p>It might be a stupid question, but I can't get it to work..</p>
<p><strong>Problem</strong><br>
I have no idea how to link my image on the frontend with the url from the database.</p>
<p><strong>Situation</strong><br>
I've created a Custom Post Type called 'Banners'. On each post I'm able to add a featured image. This will be saved in my database. Also on each post edit page, there is a input area for the banner_url. There I give my banner the link where it should go after clicking on it on the frontend. I'm able now to display the image I want on the page I want. But now I need to get the url out off the database and connent it to my image.</p>
<p><strong>Code</strong></p>
<pre><code><?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) { ?>
<?php while ( $get_banner->have_posts() ) : $get_banner->the_post(); ?>
<div class="container" align="center"><a href=""><?php echo the_post_thumbnail(); ?></a></div>
<?php endwhile; ?>
<?php }
wp_reset_postdata();
}
?>
</code></pre>
<p><strong>Question</strong><br>
My question is: How do I get the banner_url out of the database? And how am I able to get it to work with the image?</p>
<p>Thanks in advance!</p>
<p><strong>EDIT PROBLEM SOLVED</strong><br>
Thanks to Abdul Awal</p>
<pre><code><?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) : while ( $get_banner->have_posts() ) : $get_banner->the_post();
$output = '<div class="container" align="center"><a href="'.get_post_meta( get_the_ID(), 'banner_link', true ).'">'.get_the_post_thumbnail().'</a></div>';
endwhile;
endif;
wp_reset_postdata();
return $output;
}
?>
</code></pre>
| [
{
"answer_id": 260855,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 1,
"selected": false,
"text": "<p>You are looking for <code>get_post_meta()</code></p>\n\n<p>Your loop should look like:</p>\n\n<pre><c... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115316/"
] | It might be a stupid question, but I can't get it to work..
**Problem**
I have no idea how to link my image on the frontend with the url from the database.
**Situation**
I've created a Custom Post Type called 'Banners'. On each post I'm able to add a featured image. This will be saved in my database. Also on each post edit page, there is a input area for the banner\_url. There I give my banner the link where it should go after clicking on it on the frontend. I'm able now to display the image I want on the page I want. But now I need to get the url out off the database and connent it to my image.
**Code**
```
<?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) { ?>
<?php while ( $get_banner->have_posts() ) : $get_banner->the_post(); ?>
<div class="container" align="center"><a href=""><?php echo the_post_thumbnail(); ?></a></div>
<?php endwhile; ?>
<?php }
wp_reset_postdata();
}
?>
```
**Question**
My question is: How do I get the banner\_url out of the database? And how am I able to get it to work with the image?
Thanks in advance!
**EDIT PROBLEM SOLVED**
Thanks to Abdul Awal
```
<?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) : while ( $get_banner->have_posts() ) : $get_banner->the_post();
$output = '<div class="container" align="center"><a href="'.get_post_meta( get_the_ID(), 'banner_link', true ).'">'.get_the_post_thumbnail().'</a></div>';
endwhile;
endif;
wp_reset_postdata();
return $output;
}
?>
``` | Do you need to query only the items that has `banner_link` value set to `https://www.mypage.com` ?
If no, you can remove the `meta_query` part from your query.
```
<?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) { ?>
<?php while ( $get_banner->have_posts() ) : $get_banner->the_post(); ?>
<div class="container" align="center"><a href="<?php echo get_post_meta( $post->ID, 'banner_link', true ); ?>"><?php the_post_thumbnail(); ?></a></div>
<?php endwhile; ?>
<?php }
wp_reset_postdata();
}
?>
```
**UPDATE**
As you're using it inside a plugin. You can do like the following:
```
<?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) : while ( $get_banner->have_posts() ) : $get_banner->the_post();
$output = '<div class="container" align="center"><a href="'.get_post_meta( $post->ID, 'banner_link', true ).'">'.get_the_post_thumbnail().'</a></div>';
endwhile;
endif;
wp_reset_postdata();
return $output;
}
?>
```
And then call it anywhere with `<?php echo wptutsplus_home_page_banner(); ?>`
Let me know if it works. |
260,871 | <p>I'm trying to display content from SQL tables, using <code>$wpdb</code> object.
Problem is, whatever I try using it in my query, it prints a SQL error.
What I tried to do is a little more complex than what I'll show you, but I progressively simplified my query to see where the error could come from, but never found.</p>
<p>So here's what I tried last:</p>
<pre><code><?php
global $wpdb;
$wpdb->show_errors();
$tableCustom = 'join_users_defis';
$requeteAffichage = $wpdb->get_results('
SELECT *
FROM $wpdb->postmeta
');
var_dump($requeteAffichage);
?>
</code></pre>
<p>To me, it's supposed to dump the content of the table <code>{$table_prefix}_postmeta</code> (I tried with others tables), which is a standard WordPress table. But instead, it outputs the following error (thanks to <code>$wpdb->show_errors();</code>):</p>
<blockquote>
<p>WordPress database error : [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near <code>->_posts</code> at line 2]</p>
</blockquote>
<p>My current installation runs locally (<code>XAMPP</code>), with <code>MariaDB 10.1.16 / Apache / PHP 5.6.24</code></p>
<p>To be sure, I tried querying directly with my WordPress installation prefix, and it worked.</p>
<p>Is it an issue with my installation, or something I missed ? I could use some help on this.</p>
| [
{
"answer_id": 260874,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 3,
"selected": true,
"text": "<p>its a syntax error according to error message. starements like below might work for you.</p>\n\n<pre><code>gl... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105987/"
] | I'm trying to display content from SQL tables, using `$wpdb` object.
Problem is, whatever I try using it in my query, it prints a SQL error.
What I tried to do is a little more complex than what I'll show you, but I progressively simplified my query to see where the error could come from, but never found.
So here's what I tried last:
```
<?php
global $wpdb;
$wpdb->show_errors();
$tableCustom = 'join_users_defis';
$requeteAffichage = $wpdb->get_results('
SELECT *
FROM $wpdb->postmeta
');
var_dump($requeteAffichage);
?>
```
To me, it's supposed to dump the content of the table `{$table_prefix}_postmeta` (I tried with others tables), which is a standard WordPress table. But instead, it outputs the following error (thanks to `$wpdb->show_errors();`):
>
> WordPress database error : [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near `->_posts` at line 2]
>
>
>
My current installation runs locally (`XAMPP`), with `MariaDB 10.1.16 / Apache / PHP 5.6.24`
To be sure, I tried querying directly with my WordPress installation prefix, and it worked.
Is it an issue with my installation, or something I missed ? I could use some help on this. | its a syntax error according to error message. starements like below might work for you.
```
global $wpdb;
$wpdb->show_errors();
$tableCustom = 'join_users_defis';
$sql = "SELECT * FROM {$wpdb->postmeta}";
$requeteAffichage = $wpdb->get_row( $sql );
//or $requeteAffichage = $wpdb->get_results( $sql );
var_dump($requeteAffichage);
``` |
260,893 | <p>I'm trying to create a dropdown of WordPress authors, with links to their author page.</p>
<p>Here is my current code:</p>
<pre><code><?php wp_dropdown_users(array('who'=>'authors')); ?>
</code></pre>
<p>I've got a similar dropdown for my archives, which is below (and works). </p>
<pre><code><select name="archive-dropdown" id="archives-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Month' ) ); ?></option>
<?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option','show_post_count' => 1 ) ); ?>
</select>
</code></pre>
<p>Right now, the authors just show under the dropdown, but they don't link to their pages. I tried adapting the archive code to my author code, but I don't get anything to work. Here's what I was trying, but it doesn't work:</p>
<pre><code><select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php wp_dropdown_users(array('who'=>'authors')); ?>
</select>
</code></pre>
<p>I'm still pretty junior with my WordPress coding. Any insight would be great! I'm hoping I can help others if this gets solved for my situation.</p>
<p>Thanks!</p>
| [
{
"answer_id": 260904,
"author": "Sam",
"author_id": 115586,
"author_profile": "https://wordpress.stackexchange.com/users/115586",
"pm_score": 3,
"selected": true,
"text": "<p>I could be wrong as I don't know how Wordpress controls the dropdown menu but looks like it could be only return... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115915/"
] | I'm trying to create a dropdown of WordPress authors, with links to their author page.
Here is my current code:
```
<?php wp_dropdown_users(array('who'=>'authors')); ?>
```
I've got a similar dropdown for my archives, which is below (and works).
```
<select name="archive-dropdown" id="archives-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Month' ) ); ?></option>
<?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option','show_post_count' => 1 ) ); ?>
</select>
```
Right now, the authors just show under the dropdown, but they don't link to their pages. I tried adapting the archive code to my author code, but I don't get anything to work. Here's what I was trying, but it doesn't work:
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php wp_dropdown_users(array('who'=>'authors')); ?>
</select>
```
I'm still pretty junior with my WordPress coding. Any insight would be great! I'm hoping I can help others if this gets solved for my situation.
Thanks! | I could be wrong as I don't know how Wordpress controls the dropdown menu but looks like it could be only returning a name of the author and not a link to their page.
I have tested the below code in a Wordpress site environment and works including linking to the authors page.
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php
// loop through the users
$users = get_users('role=author');
foreach ($users as $user)
{
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
?>
</select>
```
[](https://i.stack.imgur.com/S1FeV.png)
Added update for making sure the authors have post and then added on administrator not sure how to combine the two roles without doing a duel foreach
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php
// loop through the users
$users = get_users('role=author');
foreach ($users as $user)
{
// get user who have posts only
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
$users = get_users('role=administrator');
foreach ($users as $user)
{
// get user who have posts only
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
?>
</select>
``` |
260,916 | <p>Sorry to have to ask this, but I have searched and searched and can't seem to figure out how to do this...</p>
<p>I have this code on a custom PHP page:</p>
<pre><code>(code placeholder spot which I will reference later)
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
order by r.race_date;
");
foreach ( $races as $race ) {
echo $race->race_id . ',' . $race->race_name . ',' . $race->race_date;
}
</code></pre>
<p>Which displays something like this:</p>
<pre><code>1, Resolution, 2017-01-17
2, Sea 2 Sea, 2017-03-02
3, Earth Day, 2017-04-22
</code></pre>
<p>But, here's my question...</p>
<p>I need to be able to add a custom row at the beginning of the array.</p>
<p>So, I need to be able to add some code at the exact place above where I have <strong>(code placeholder spot which I will reference later)</strong> which will insert anything I want as the first row of the array.</p>
<p>I want to be able add a custom row, for example, "id, name, date" so that when I run the display code it will display this:</p>
<pre><code>id, name, date
1, Resolution, 2017-01-17
2, Sea 2 Sea, 2017-03-02
3, Earth Day, 2017-04-22
</code></pre>
<p>I've tried a few things I've found online but nothing seems to work.</p>
<p>And no, a simple 'echo' command won't do. I don't want to go into details why (because it will make this post very long), but in my case I need the custom row added to the array.</p>
<p>Please help!</p>
<p>=================== EDIT (ANSWERED!!) ======================</p>
<p>Thanks to @Abdul I got it to work with this code:</p>
<pre><code>$races_to_send = array(array ('name', 'id', 'date'));
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
order by r.race_name
,r.race_date;
", ARRAY_N);
$merged_arr = array_merge($races_to_send, $races);
foreach ( $merged_arr as $race ) {
echo $race['0'] . ',' . $race['1'] . ',' . $race['2'];
}
</code></pre>
| [
{
"answer_id": 260904,
"author": "Sam",
"author_id": 115586,
"author_profile": "https://wordpress.stackexchange.com/users/115586",
"pm_score": 3,
"selected": true,
"text": "<p>I could be wrong as I don't know how Wordpress controls the dropdown menu but looks like it could be only return... | 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260916",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112305/"
] | Sorry to have to ask this, but I have searched and searched and can't seem to figure out how to do this...
I have this code on a custom PHP page:
```
(code placeholder spot which I will reference later)
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
order by r.race_date;
");
foreach ( $races as $race ) {
echo $race->race_id . ',' . $race->race_name . ',' . $race->race_date;
}
```
Which displays something like this:
```
1, Resolution, 2017-01-17
2, Sea 2 Sea, 2017-03-02
3, Earth Day, 2017-04-22
```
But, here's my question...
I need to be able to add a custom row at the beginning of the array.
So, I need to be able to add some code at the exact place above where I have **(code placeholder spot which I will reference later)** which will insert anything I want as the first row of the array.
I want to be able add a custom row, for example, "id, name, date" so that when I run the display code it will display this:
```
id, name, date
1, Resolution, 2017-01-17
2, Sea 2 Sea, 2017-03-02
3, Earth Day, 2017-04-22
```
I've tried a few things I've found online but nothing seems to work.
And no, a simple 'echo' command won't do. I don't want to go into details why (because it will make this post very long), but in my case I need the custom row added to the array.
Please help!
=================== EDIT (ANSWERED!!) ======================
Thanks to @Abdul I got it to work with this code:
```
$races_to_send = array(array ('name', 'id', 'date'));
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
order by r.race_name
,r.race_date;
", ARRAY_N);
$merged_arr = array_merge($races_to_send, $races);
foreach ( $merged_arr as $race ) {
echo $race['0'] . ',' . $race['1'] . ',' . $race['2'];
}
``` | I could be wrong as I don't know how Wordpress controls the dropdown menu but looks like it could be only returning a name of the author and not a link to their page.
I have tested the below code in a Wordpress site environment and works including linking to the authors page.
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php
// loop through the users
$users = get_users('role=author');
foreach ($users as $user)
{
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
?>
</select>
```
[](https://i.stack.imgur.com/S1FeV.png)
Added update for making sure the authors have post and then added on administrator not sure how to combine the two roles without doing a duel foreach
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php
// loop through the users
$users = get_users('role=author');
foreach ($users as $user)
{
// get user who have posts only
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
$users = get_users('role=administrator');
foreach ($users as $user)
{
// get user who have posts only
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
?>
</select>
``` |
260,924 | <p>I'm trying to clean up a WordPress website that's been hacked. I noticed that the <code>.htaccess</code> file has some suspect looking regular expressions, but my regex skills are pretty weak (time to learn I guess). I've tried replacing the <code>.htaccess</code> file with the default WordPress <code>.htaccess</code>, but it gets rewritten immediately and automatically. What I need to know is what's going on with this code:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)-.*..*$ ?$1$3=$2&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)=[0-9]+$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)..*&_.*_.*=(.*)Q(.*)J[0-9]+.*TXF[0-9]+.*FLK.*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)..*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F.*%[0-9]+F&$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F.*%[0-9]+F$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F&$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+).*[0-9]+..*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)..*$ ?$1$3=$2&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F&#[0-9]+;.*=.*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)-([^\d\/]+)_.*_([0-9]+)$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>If the <code>.htaccess</code> has been compromised, do you have any suggestions for securing it?</p>
<p>I did a fresh WordPress install, updated/reinstalled all plugins, reset passwords, installed captchas for logins, moved the WordPress install to a different directory, etc. Website seemed to be fine for a few days, but was hacked again. So frustrating!</p>
| [
{
"answer_id": 262364,
"author": "Piero",
"author_id": 114816,
"author_profile": "https://wordpress.stackexchange.com/users/114816",
"pm_score": -1,
"selected": false,
"text": "<p>One of the best solution I've found is to install <a href=\"https://it.wordpress.org/plugins/wordfence/\" re... | 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260924",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115935/"
] | I'm trying to clean up a WordPress website that's been hacked. I noticed that the `.htaccess` file has some suspect looking regular expressions, but my regex skills are pretty weak (time to learn I guess). I've tried replacing the `.htaccess` file with the default WordPress `.htaccess`, but it gets rewritten immediately and automatically. What I need to know is what's going on with this code:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)-.*..*$ ?$1$3=$2&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)=[0-9]+$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)..*&_.*_.*=(.*)Q(.*)J[0-9]+.*TXF[0-9]+.*FLK.*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)..*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F.*%[0-9]+F&$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F.*%[0-9]+F$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F&$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+).*[0-9]+..*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)..*$ ?$1$3=$2&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F&#[0-9]+;.*=.*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)-([^\d\/]+)_.*_([0-9]+)$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
If the `.htaccess` has been compromised, do you have any suggestions for securing it?
I did a fresh WordPress install, updated/reinstalled all plugins, reset passwords, installed captchas for logins, moved the WordPress install to a different directory, etc. Website seemed to be fine for a few days, but was hacked again. So frustrating! | ### About Hacked sites:
First of all, let's be clear about issues related to hacking:
>
> If your site was genuinely hacked, then in short of completely erasing all the files and then reinstalling the server (not just WordPress) with new passwords, updating all files and identifying and removing previous loop holes that caused the site to be hacked in the first place, nothing else will confirm that the site will not be hacked again using the same loop holes.
>
>
>
### About the `.htaccess` modification:
To me, your `.htaccess` modification doesn't look like the result of hacking, instead it looks like a piece of WordPress CODE (either from a Plugin, or theme) that is rewriting the `.htaccess` file because of URL rewrites.
Check out this sample from your `.htaccess` CODE:
```
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)-.*..*$ ?$1$3=$2&%{QUERY_STRING}[L]
```
This line is basically transforming a URL that looks like this (for example):
```
example.com/something-12-34-something-else.html?query=string
```
to adds query string (internally to the main `index.php`) that looks like this:
```
?something34=12&query=string
```
So, basically I don't see how a hacker will gain anything from this. It's still possible, but unlikely.
To test it is indeed being rewritten by WordPress this way, you may do the following test:
1. Go to `wp-admin -> Settings -> Permalinks` & click `Save Changes` button.
2. Rewrite `.htaccess` with the default WordPress `.htaccess` CODE.
3. Now, go to `wp-admin -> Settings -> Permalinks` again and click `Save Changes` button.
If your `.htaccess` file is writable by WordPress (web server) and if that `.htaccess` CODE was being generated by WordPress, then after the above process, your default WordPress `.htaccess` will be changed immediately to the one you've posted.
### What to do next?
If you've successfully identified the changes to be made by WordPress, then you may detect which plugin or theme is doing it, by again following the above procedure after disabling each installed plugin one at a time.
Once the responsible plugin is disabled, the above procedure will not produce that change in the `.htaccess` file anymore. Then you'll know which plugin is doing it, and perhaps will have a better understanding of why it's doing it. e.g. whether it is a feature or the result of malicious activity.
If no plugin is found to be doing it, then you may do the same with the theme by activating a WordPress core theme (e.g. Twenty Seventeen).
If none of the above works, then I guess your next option is to hire an expert and allow him to examine your site. |
260,933 | <p>In order to increase my theme's accessibility, I want to add the <code>aria-current="page"</code> attribute to the menu item that has the class <code>.current_page_item</code>.</p>
<p>As of right now, I am doing this via jQuery using the following:</p>
<pre><code>var currentitem = $( '.current_page_item > a' );
currentitem.attr( 'aria-current', 'page' );
</code></pre>
<p>While this does what I want it to do, I would prefer that PHP handles this particular thing.</p>
<p>I know I can do this either with a custom Nav Walker class or with a filter to <code>nav_menu_link_attributes</code>. Unfortunately I have not seen any code even remotely near what I want to do.</p>
<pre><code>function my_menu_filter( $atts, $item, $args, $depth ) {
// Select the li.current_page_item element
// Add `aria-current="page"` to child a element
}
add_filet( 'nav_menu_link_attributes', 'my_menu_filter', 10, 3 );
</code></pre>
<p>Any help in writing this filter would be appreciated.</p>
| [
{
"answer_id": 260934,
"author": "Yoav Kadosh",
"author_id": 25959,
"author_profile": "https://wordpress.stackexchange.com/users/25959",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the filter <code>nav_menu_link_attributes</code> to achieve that:</p>\n\n<pre><code>function ... | 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260933",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80069/"
] | In order to increase my theme's accessibility, I want to add the `aria-current="page"` attribute to the menu item that has the class `.current_page_item`.
As of right now, I am doing this via jQuery using the following:
```
var currentitem = $( '.current_page_item > a' );
currentitem.attr( 'aria-current', 'page' );
```
While this does what I want it to do, I would prefer that PHP handles this particular thing.
I know I can do this either with a custom Nav Walker class or with a filter to `nav_menu_link_attributes`. Unfortunately I have not seen any code even remotely near what I want to do.
```
function my_menu_filter( $atts, $item, $args, $depth ) {
// Select the li.current_page_item element
// Add `aria-current="page"` to child a element
}
add_filet( 'nav_menu_link_attributes', 'my_menu_filter', 10, 3 );
```
Any help in writing this filter would be appreciated. | You may target the `current_page_item` CSS class or you may target the `current-menu-item` CSS class instead. `current_page_item` class may not be present for all kinds of menu item. Read [the answer here](https://wordpress.stackexchange.com/questions/14978/whats-the-difference-between-current-page-item-and-current-menu-item) to know why.
Whichever CSS class you choose, you may use the CODE like the following to set the attribute:
```
add_filter( 'nav_menu_link_attributes', 'wpse260933_menu_atts_filter', 10, 3 );
function wpse260933_menu_atts_filter( $atts, $item, $args ) {
if( in_array( 'current-menu-item', $item->classes ) ) {
$atts['aria-current'] = 'page';
}
return $atts;
}
``` |
260,941 | <p>We all know that <code>ignore_sticky_posts</code> is used to exclude sticky post from your custom query.</p>
<p>But why on <a href="https://developer.wordpress.org/themes/functionality/sticky-posts/" rel="nofollow noreferrer">WordPress Theme Development documentation</a>, they use <code>ignore_sticky_posts</code> in querying sticky posts?</p>
<pre class="lang-php prettyprint-override"><code>$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );
</code></pre>
<p>This is so confusing and doesn't make any sense! You want it and yet you exclude it?</p>
| [
{
"answer_id": 260951,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p>We all know that <code>ignore_sticky_posts</code> is used to exclude sticky post from your cus... | 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105000/"
] | We all know that `ignore_sticky_posts` is used to exclude sticky post from your custom query.
But why on [WordPress Theme Development documentation](https://developer.wordpress.org/themes/functionality/sticky-posts/), they use `ignore_sticky_posts` in querying sticky posts?
```php
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );
```
This is so confusing and doesn't make any sense! You want it and yet you exclude it? | >
> We all know that `ignore_sticky_posts` is used to exclude sticky post from your custom query.
>
>
>
### - No, this assumption is wrong.
---
What `ignore_sticky_posts` means:
---------------------------------
Even though in natural English, `ignore_sticky_posts` sounds like WordPress should ignore all sticky posts from the query, in reality that is not what WordPress does. Instead, you should read `'ignore_sticky_posts' => 1` argument as follows:
>
> When `ignore_sticky_posts` is set to `true` or `1`, WordPress will **ignore the procedure** of setting the sticky posts within your custom query.
>
>
>
---
What WordPress does when `ignore_sticky_posts` is not set:
----------------------------------------------------------
To clearly understand what `'ignore_sticky_posts' => 1` does, you need to understand what WordPress does when `ignore_sticky_posts` argument is not set or it's set to `false` or `0` (by default):
1. If there are posts within the query result that are part of stick posts, WordPress will push them to the top of the query result.
2. If any sticky post is not present within the query result, WordPress will get all those sticky posts from the database again and set them to the top of the query result.
So when the argument is set as `'ignore_sticky_posts' => 1`, WordPress simply **ignores the above procedure**, that's all. It doesn't exclude them specifically. For that you need to set `post__not_in` argument.
---
Explanation of the codex example:
---------------------------------
Now, let's come to the example from the codex:
```
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );
```
Here codex is only setting `'ignore_sticky_posts' => 1` **to be efficient, nothing more**. Even without having it, you will get the same expected result:
```
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' )
);
$query = new WP_Query( $args );
```
However, in this case, since `'ignore_sticky_posts' => 1` argument is not set, WordPress will needlessly do all those procedure of setting sticky posts to the top of the results, even though all of these results (from this example) are only sticky posts.
---
Best way to learn something in WordPress is to examine the core CODE. So for even clearer understanding, examine [this part of WordPress CODE](https://github.com/WordPress/WordPress/blob/4.7-branch/wp-includes/class-wp-query.php#L2941-L2980). |
260,952 | <p>I would like to have the possibility to create "sub single pages" to display detailed content in a custom post type.
Is there a way to generate pages, with a specific template with a URL of this type:</p>
<pre><code>domain.com/custom-post-type-slug/single-slug/sub-single-slug/
</code></pre>
<p>Note : I need multiple sub-single pages for each section of my post (content added via ACF). The slug doesn't need to be dynamic because all of my sections are the same for each post.</p>
<p>Thank you!</p>
| [
{
"answer_id": 260957,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 2,
"selected": false,
"text": "<p>First, you need to register the custom post type so that it has hierarchy, i.e. a post can have a parent post... | 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260952",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73871/"
] | I would like to have the possibility to create "sub single pages" to display detailed content in a custom post type.
Is there a way to generate pages, with a specific template with a URL of this type:
```
domain.com/custom-post-type-slug/single-slug/sub-single-slug/
```
Note : I need multiple sub-single pages for each section of my post (content added via ACF). The slug doesn't need to be dynamic because all of my sections are the same for each post.
Thank you! | Here is the solution (origin : <http://www.placementedge.com/blog/create-post-sub-pages/>)
```
// Fake pages' permalinks and titles. Change these to your required sub pages.
$my_fake_pages = array(
'reviews' => 'Reviews',
'purchase' => 'Purchase',
'author' => 'Author Bio'
);
add_filter('rewrite_rules_array', 'fsp_insertrules');
add_filter('query_vars', 'fsp_insertqv');
// Adding fake pages' rewrite rules
function wpse_261271_insertrules($rules)
{
global $my_fake_pages;
$newrules = array();
foreach ($my_fake_pages as $slug => $title)
$newrules['books/([^/]+)/' . $slug . '/?$'] = 'index.php?books=$matches[1]&fpage=' . $slug;
return $newrules + $rules;
}
// Tell WordPress to accept our custom query variable
function wpse_261271_insertqv($vars)
{
array_push($vars, 'fpage');
return $vars;
}
// Remove WordPress's default canonical handling function
remove_filter('wp_head', 'rel_canonical');
add_filter('wp_head', 'fsp_rel_canonical');
function wpse_261271_rel_canonical()
{
global $current_fp, $wp_the_query;
if (!is_singular())
return;
if (!$id = $wp_the_query->get_queried_object_id())
return;
$link = trailingslashit(get_permalink($id));
// Make sure fake pages' permalinks are canonical
if (!empty($current_fp))
$link .= user_trailingslashit($current_fp);
echo '<link rel="canonical" href="'.$link.'" />';
}
```
DO NOT forget to flush your permalinks! Go to Settings > Permalinks > Save to flush |
260,998 | <p>I have custom post type of <code>portfolio</code> and I would like to be able to re-use most of the templating, but change to <code>content-portfolio</code> when the page is a custom post type named <code>portfolio</code>.</p>
<p>At present this is not working, so I'm not sure if I need to add Custom Post Types in the Main Query or add it inside the while loop? </p>
<p><strong>index.php CODE:</strong></p>
<pre><code>get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : ?>
<header>
<?php if( single_post_title( '', false ) ) : ?>
<h1 class="page-title"><?php single_post_title(); ?></h1>
<?php else : ?>
<h1 class="page-title">
<?php echo get_bloginfo( 'name' ); ?>
</h1>
<?php endif; ?>
</header>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
if(get_post_type()) : {
get_template_part( 'template-parts/content', get_post_type() );
elseif :
get_template_part( 'template-parts/content', get_post_format() );
endif;
}
?>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 260966,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 1,
"selected": false,
"text": "<p>Usually setting a post as sticky post sets it to the featured area. From wp-admin editor, set a post as stick... | 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260998",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105914/"
] | I have custom post type of `portfolio` and I would like to be able to re-use most of the templating, but change to `content-portfolio` when the page is a custom post type named `portfolio`.
At present this is not working, so I'm not sure if I need to add Custom Post Types in the Main Query or add it inside the while loop?
**index.php CODE:**
```
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : ?>
<header>
<?php if( single_post_title( '', false ) ) : ?>
<h1 class="page-title"><?php single_post_title(); ?></h1>
<?php else : ?>
<h1 class="page-title">
<?php echo get_bloginfo( 'name' ); ?>
</h1>
<?php endif; ?>
</header>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
if(get_post_type()) : {
get_template_part( 'template-parts/content', get_post_type() );
elseif :
get_template_part( 'template-parts/content', get_post_format() );
endif;
}
?>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
``` | I note you are using the **Minamaze** theme, correct? The problem here is the featured area, is exactly that, an area to manually enter featured content. You cannot automatically add posts to these areas.
To configure them, you need to go into the admin, choose appearance, then customize.
In here, choose Theme Options, then Homepage (Featured) and this will open the section to edit the content of the three areas. |
261,038 | <p>I'd like to limit search to characters used on the English language + numbers.
The reason is that looking at the slowest queries on mysql log i found most come from searches in Arab, Russian and Chinese characters, so i'd like to skip them and display an error message instead.</p>
| [
{
"answer_id": 261303,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 2,
"selected": false,
"text": "<p>You would do this by putting in a validation function in PHP to test the input against a regular expression lik... | 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/261038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77283/"
] | I'd like to limit search to characters used on the English language + numbers.
The reason is that looking at the slowest queries on mysql log i found most come from searches in Arab, Russian and Chinese characters, so i'd like to skip them and display an error message instead. | This solution filters search strings by applying a regular expression which only matches characters from the Common and Latin Unicode scripts.
---
Matching Latin Characters with Regular Expressions
--------------------------------------------------
I just [had my mind blown over at Stack Overflow](https://stackoverflow.com/questions/43015495). As it turns out, regular expressions have [a mechanism](http://www.regular-expressions.info/unicode.html#script) to match entire Unicode categories, including values to specify entire [Unicode "scripts"](https://wikipedia.org/wiki/Script_(Unicode)), each corresponding to groups of characters used in different writing systems.
This is done by using the `\p` meta-character followed by a Unicode category identifier in curly braces - so `[\p{Common}\p{Latin}]` matches a single character in either the [Latin or Common scripts](https://wikipedia.org/wiki/List_of_Unicode_characters#Latin_script) - this includes punctuation, numerals, and miscellaneous symbols.
As [@Paul 'Sparrow Hawk' Biron points out](https://wordpress.stackexchange.com/a/261430/25324), the `u` [pattern modifier flag](http://php.net/manual/en/reference.pcre.pattern.modifiers.php) should be set at the end of the regular expression in order for PHP's PCRE functions to treat the subject string as `UTF-8` Unicode encoded.
All together then, the pattern
```
/^[\p{Latin}\p{Common}]+$/u
```
will match an entire string composed of one or more characters in the Latin and Common Unicode scripts.
---
Filtering the Search String
---------------------------
A good place to intercept a search string is [the `pre_get_posts` action](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) as it fires immediately before WordPress executes the query. With **more care**, this could also be accomplished using [a `request` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/request).
```
function wpse261038_validate_search_characters( $query ) {
// Leave admin, non-main query, and non-search queries alone
if( is_admin() || !$query->is_main_query() || !$query->is_seach() )
return;
// Check if the search string contains only Latin/Common Unicode characters
$match_result = preg_match( '/^[\p{Latin}\p{Common}]+$/u', $query->get( 's' ) );
// If the search string only contains Latin/Common characters, let it continue
if( 1 === $match_result )
return;
// If execution reaches this point, the search string contains non-Latin characters
//TODO: Handle non-Latin search strings
//TODO: Set up logic to display error message
}
add_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );
```
---
Responding to Disallowed Searches
---------------------------------
Once it's been determined that a search string contains non-Latin characters, you can use `WP_Query::set()` in order to modify the query by changing it's named [query vars](https://codex.wordpress.org/WordPress_Query_Vars) - thus affecting the SQL query WordPress subsequently composes and executes.
The most relevant query variables are probably the following:
* `s` is the query variable corresponding to a search string. Setting it to `null` or an empty string (`''`) will result in the WordPress no longer treating the query as a search - often times this results in an archive template displaying all posts or the front-page of the site, depending on the values of the other query vars. Setting it to a single space (`' '`), however, will result in WordPress recognizing it as a search, and thus attempting to display the `search.php` template.
* `page_id` could be used to direct the user to a specific page of your choice.
* `post__in` can restrict the query to a specific selection of posts. By setting it to an array with an impossible post ID, [it can serve as a measure to ensure that the query returns absolutely nothing](https://wordpress.stackexchange.com/questions/140692/can-i-force-wp-query-to-return-no-results).
The above in mind, you might do the following in order to respond to a bad search by loading the `search.php` template with no results:
```
function wpse261038_validate_search_characters( $query ) {
// Leave admin, non-main query, and non-search queries alone
if( is_admin() || !$query->is_main_query() || !$query->is_seach() )
return;
// Check if the search string contains only Latin/Common Unicode characters
$match_result = preg_match( '/^[\p{Latin}\p{Common}]+$/u', $query->get( 's' ) );
// If the search string only contains Latin/Common characters, let it continue
if( 1 === $match_result )
return;
$query->set( 's', ' ' ); // Replace the non-latin search with an empty one
$query->set( 'post__in', array(0) ); // Make sure no post is ever returned
//TODO: Set up logic to display error message
}
add_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );
```
---
Displaying an Error
-------------------
The way in which you actually display the error message is highly dependent on your application and the abilities of your theme - there are many ways which this can be done. If your theme calls `get_search_form()` in it's search template, the easiest solution is probably to use a [`pre_get_search_form` action](https://developer.wordpress.org/reference/hooks/pre_get_search_form/) hook to output your error immediately above the search form:
```
function wpse261038_validate_search_characters( $query ) {
// Leave admin, non-main query, and non-search queries alone
if( is_admin() || !$query->is_main_query() || !$query->is_seach() )
return;
// Check if the search string contains only Latin/Common Unicode characters
$match_result = preg_match( '/^[\p{Latin}\p{Common}]+$/u', $query->get( 's' ) );
// If the search string only contains Latin/Common characters, let it continue
if( 1 === $match_result )
return;
$query->set( 's', ' ' ); // Replace the non-latin search with an empty one
$query->set( 'post__in', array(0) ); // Make sure no post is ever returned
add_action( 'pre_get_search_form', 'wpse261038_display_search_error' );
}
add_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );
function wpse261038_display_search_error() {
echo '<div class="notice notice-error"><p>Your search could not be completed as it contains characters from non-Latin alphabets.<p></div>';
}
```
Some other possibilities for displaying an error message include:
* If your site uses JavaScript which can display "flash" or "modal" messages (or you add such abilities on your own), add to it the logic to display messages on page-load when a specific variable is set, then add a `wp_enqueue_script` hook with a `$priority` larger than that which enqueues that JavaScript, and use `wp_localize_script()` to set that variable to include your error message.
* Use `wp_redirect()` to send the user to the URL of your choice (this method requires an additional page load).
* Set a PHP variable or invoke a method which will inform your theme/plugin about the error such that it may display it where appropriate.
* Set the `s` query variable to `''` instead of `' '` and use `page_id` in place of `post__in` in order to return a page of your choosing.
* Use a [`loop_start` hook](https://developer.wordpress.org/reference/hooks/loop_start/) to inject a fake `WP_Post` object containing your error into the query results - this is most definitely an ugly hack and may not look right with your particular theme, but it has the potentially desirable side effect of suppressing the "No Results" message.
* Use a `template_include` filter hook to swap out the search template with a custom one in your theme or plugin which displays your error.
Without examining the theme in question, it's difficult to determine which route you should take. |
261,042 | <p>First, I want to clarify - <strong>this is not a CSS question.</strong> </p>
<p>I want to change the data that is showing of the widget, when its in closed / open mode inside the wp-admin, in a sidebar or a page builder. Here is an image to better explain.</p>
<p><a href="https://i.stack.imgur.com/bBXNY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bBXNY.jpg" alt="enter image description here"></a></p>
<p>I want to be able to add something / remove from the title of the widget dynamically and use widget $instance to do so</p>
<p><strong>The desired result:</strong><br>
Add a small info label stating mobile / desktop / both - which is an option picked inside that specific widget</p>
<p>Ideas anyone?</p>
<p><em>UPDATE</em><br>
<strong>Since i see some intrest in a solution to this question:</strong><br>
@cjbj solution works beautifully but only in the sidebar and only partially:</p>
<pre><code>add_filter ('dynamic_sidebar_params','wpse261042_change_widget_title');
function wpse261042_change_widget_title ($params) {
$widget_id = $params[0]['widget_id'];
$widget_instance = strrchr ($widget_id, '-');
$wlen = strlen ($widget_id);
$ilen = strlen ($widget_instance);
$widget_name = substr ($widget_id,0,$wlen-$ilen);
$widget_instance = substr ($widget_instance,1);
// get the data
$widget_instances = get_option('widget_' . $widget_name);
$data = $widget_instances[$widget_instance];
$use_mobile = $data['use_mobile']; // option inside my widget
if($use_mobile == 'yes') {$string = 'desktop / mobile';} else {$string = 'desktop only';}
$params[0]['widget_name'] .= $string;
return $params;
}
</code></pre>
<p>However.. you cannot insert any html in that string (or at least i couldnt)</p>
<p>Would update if i find a working solution.</p>
| [
{
"answer_id": 261346,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Let's first see whether it is possible to change the information that is displayed in the widget titles in admin... | 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/261042",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7990/"
] | First, I want to clarify - **this is not a CSS question.**
I want to change the data that is showing of the widget, when its in closed / open mode inside the wp-admin, in a sidebar or a page builder. Here is an image to better explain.
[](https://i.stack.imgur.com/bBXNY.jpg)
I want to be able to add something / remove from the title of the widget dynamically and use widget $instance to do so
**The desired result:**
Add a small info label stating mobile / desktop / both - which is an option picked inside that specific widget
Ideas anyone?
*UPDATE*
**Since i see some intrest in a solution to this question:**
@cjbj solution works beautifully but only in the sidebar and only partially:
```
add_filter ('dynamic_sidebar_params','wpse261042_change_widget_title');
function wpse261042_change_widget_title ($params) {
$widget_id = $params[0]['widget_id'];
$widget_instance = strrchr ($widget_id, '-');
$wlen = strlen ($widget_id);
$ilen = strlen ($widget_instance);
$widget_name = substr ($widget_id,0,$wlen-$ilen);
$widget_instance = substr ($widget_instance,1);
// get the data
$widget_instances = get_option('widget_' . $widget_name);
$data = $widget_instances[$widget_instance];
$use_mobile = $data['use_mobile']; // option inside my widget
if($use_mobile == 'yes') {$string = 'desktop / mobile';} else {$string = 'desktop only';}
$params[0]['widget_name'] .= $string;
return $params;
}
```
However.. you cannot insert any html in that string (or at least i couldnt)
Would update if i find a working solution. | Background:
-----------
The reason why filtering with `dynamic_sidebar_params` doesn't work with `HTML` is because WordPress strips `HTML` from Widget Heading in [`wp_widget_control()`](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L216) function like this:
```
$widget_title = esc_html( strip_tags( $sidebar_args['widget_name'] ) );
```
WordPress also strips `HTML` in default JavaScript in [`wp-admin/js/widgets.js`](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/widgets.js#L485)
So without a customised solution, there is no default filter or option either with PHP or with JavaScript to achieve what you want.
Custom PHP Solution:
--------------------
A custom PHP solution is possible that'll only work in `wp-admin -> Appearance -> Widgets`, but not in `Customizer -> Widgets`.
WordPress adds [`wp_widget_control()` function](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L169-L272) (that generates Widget Control UI) with `dynamic_sidebar_params` hook, so it's possible to override it using this filter hook. However, in customizer, WordPress calls [`wp_widget_control()` function](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L169-L272) directly, so this solution will not work for the customizer.
The solution works like the following (add this code in a custom plugin):
```
add_filter( 'dynamic_sidebar_params', 'wpse261042_list_widget_controls_dynamic_sidebar', 20 );
function wpse261042_list_widget_controls_dynamic_sidebar( $params ) {
global $wp_registered_widgets;
// we only want this in wp-admin (may need different check to enable page builder)
if( is_admin() ) {
if ( is_array( $params ) && is_array( $params[0] ) && $params[0]['id'] !== 'wp_inactive_widgets' ) {
$widget_id = $params[0]['widget_id'];
if ( $wp_registered_widgets[$widget_id]['callback'] === 'wp_widget_control' ) {
// here we are replacing wp_widget_control() function
// with our custom wpse261042_widget_control() function
$wp_registered_widgets[$widget_id]['callback'] = 'wpse261042_widget_control';
}
}
}
return $params;
}
function wpse261042_widget_control( $sidebar_args ) {
// here copy everything from the core wp_widget_control() function
// and change only the part related to heading as you need
}
```
As I said before, this solution doesn't work for the customizer and more likely to require future updates as we are overriding a core function.
Custom JavaScript Solution (Recommended):
=========================================
Fortunately, it's possible to customize this behaviour with JavaScript. WordPress updates Widget Control Heading with JavaScript anyway. To do that WordPress keeps a placeholder `in-widget-title` CSS class and updates it with the widget `title` field value from JavaScript CODE. We can manipulate this to achieve our goal.
### Related Core JS files:
First you need to know that WordPress loads [`wp-admin/js/customize-widgets.js`](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/customize-widgets.js) file (with `customize-widgets` handle) in `wp-admin -> Customize -> Widgets` (customizer) and [`wp-admin/js/widgets.js`](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/widgets.js) file (with `admin-widgets` handle) in `wp-admin -> Appearance -> Widgets` to manipulate Widget Control UI. These two files do similar operations for Widget UI markups and Widget Heading UI manipulation, but a lot of different things as well. So we need to consider that for our JavaScript based solution.
### Considerations for Customizer:
Customizer doesn't load Widget UI markup immediately after page load, instead, it loads with JavaScript when the corresponding `Widgets -> Sidebar` panel is open. So we need to manipulate the Widget UI after WordPress loads it. For example, since customizer CODE is event based, I've used the following line of CODE to set the event handler at the correct moment:
```
section.expanded.bind( onExpanded );
```
Also, customizer used AJAX to load changes immediately, that's why I've used the following line to tap into the data change:
```
control.setting.bind( updateTitle );
```
Also, I needed to tap into `widget-added` event with the following line of CODE:
```
$( document ).on( 'widget-added', add_widget );
```
### Common for Customizer & `wp-admin -> Appearance -> Widgets`:
Both the above mentioned JavaScript files trigger `widget-updated` event when an widget is updated. Although customizer does it immediately with AJAX, while traditional `Widget` admin does it after you Click the `Save` button. I've used the following line of CODE for this:
```
$( document ).on( 'widget-updated', modify_widget );
```
### Considerations for `wp-admin -> Appearance -> Widgets`:
Contrary to the customizer, traditional `Widgets` admin loads the Widget Control UI with PHP, so I've traversed the UI HTML to make the initial changes like this:
```
$( '#widgets-right div.widgets-sortables div.widget' ).each( function() { // code } );
```
Custom Plugin CODE:
===================
Following is a complete Plugin with JavaScript based solution that will work both in `wp-admin -> Appearance -> Widgets` and `Customizer -> Widgets`:
`wpse-widget-control.php` Plugin PHP file:
```
<?php
/**
* Plugin Name: Widget Control
* Plugin URI: https://wordpress.stackexchange.com/questions/261042/how-to-influence-the-information-displayed-on-widget-inside-wp-admin
* Description: Display additional info on Widget Heading in wp-admin & customizer using JS
* Author: Fayaz
* Version: 1.0
* Author URI: http://fmy.me/
*/
if( is_admin() ) {
add_action( 'current_screen', 'wpse261042_widget_screen' );
}
function wpse261042_widget_screen() {
$currentScreen = get_current_screen();
if( $currentScreen->id === 'customize' ) {
add_action( 'customize_controls_enqueue_scripts', 'wpse261042_customizer_widgets', 99 );
}
else if( $currentScreen->id === 'widgets' ) {
add_action( 'admin_enqueue_scripts', 'wpse261042_admin_widgets', 99 );
}
}
function wpse261042_customizer_widgets() {
wp_enqueue_script( 'custom-widget-heading', plugin_dir_url( __FILE__ ) . 'custom-widget-heading.js', array( 'jquery', 'customize-widgets' ) );
}
function wpse261042_admin_widgets() {
wp_enqueue_script( 'custom-widget-heading', plugin_dir_url( __FILE__ ) . 'custom-widget-heading.js', array( 'jquery', 'admin-widgets' ) );
}
```
`custom-widget-heading.js` JavaScript file:
```
(function( wp, $ ) {
var compare = {
// field to compare
field: 'title',
// value to be compared with
value: 'yes',
// heading if compare.value matches with compare.field value
heading: ' <i>(mobile/desktop)</i> ',
// alternate heading
alt_heading: ' <i>(desktop only)</i> ',
// WP adds <span class="in-widget-title"></span> in each widget heading by default
heading_selector: '.in-widget-title'
};
var widgetIdSelector = '> .widget-inside > form > .widget-id';
// heading is added as prefix of already existing heading, modify this as needed
function modify_heading( $elm, isMain ) {
var html = $elm.html();
if ( html.indexOf( compare.heading ) == -1 && html.indexOf( compare.alt_heading ) == -1 ) {
if( isMain ) {
$elm.html( compare.heading + html );
}
else {
$elm.html( compare.alt_heading + html );
}
}
};
function parseFieldSelector( widgetId ) {
return 'input[name="' + widgetIdToFieldPrefix( widgetId ) + '[' + compare.field + ']"]';
};
// @note: change this function if you don't want custom Heading change to appear for all the widgets.
// If field variable is empty, then that means that field doesn't exist for that widget.
// So use this logic if you don't want the custom heading manipulation if the field doesn't exist for a widget
function modify_widget( evt, $widget, content ) {
var field = null;
var field_value = '';
if( content ) {
field = $( content ).find( parseFieldSelector( $widget.find( widgetIdSelector ).val() ) );
}
else {
field = $widget.find( parseFieldSelector( $widget.find( widgetIdSelector ).val() ) );
}
if( field ) {
field_value = ( ( field.attr( 'type' ) != 'radio' && field.attr( 'type' ) != 'checkbox' )
|| field.is( ':checked' ) ) ? field.val() : '';
}
modify_heading( $widget.find( compare.heading_selector ), field_value == compare.value );
}
function parseWidgetId( widgetId ) {
var matches, parsed = {
number: null,
id_base: null
};
matches = widgetId.match( /^(.+)-(\d+)$/ );
if ( matches ) {
parsed.id_base = matches[1];
parsed.number = parseInt( matches[2], 10 );
} else {
parsed.id_base = widgetId;
}
return parsed;
}
function widgetIdToSettingId( widgetId ) {
var parsed = parseWidgetId( widgetId ), settingId;
settingId = 'widget_' + parsed.id_base;
if ( parsed.number ) {
settingId += '[' + parsed.number + ']';
}
return settingId;
}
function widgetIdToFieldPrefix( widgetId ) {
var parsed = parseWidgetId( widgetId ), settingId;
settingId = 'widget-' + parsed.id_base;
if ( parsed.number ) {
settingId += '[' + parsed.number + ']';
}
return settingId;
}
var api = wp.customize;
if( api ) {
// We ate in the customizer
widgetIdSelector = '> .widget-inside > .form > .widget-id';
api.bind( 'ready', function() {
function add_widget( evt, $widget ) {
var control;
control = api.control( widgetIdToSettingId( $widget.find( widgetIdSelector ).val() ) );
function updateTitle( evt ) {
modify_widget( null, $widget );
};
if ( control ) {
control.setting.bind( updateTitle );
}
updateTitle();
};
api.control.each( function ( control ) {
if( control.id && 0 === control.id.indexOf( 'widget_' ) ) {
api.section( control.section.get(), function( section ) {
function onExpanded( isExpanded ) {
if ( isExpanded ) {
section.expanded.unbind( onExpanded );
modify_widget( null, control.container.find( '.widget' ), control.params.widget_content );
}
};
if ( section.expanded() ) {
onExpanded( true );
} else {
section.expanded.bind( onExpanded );
}
} );
}
} );
$( document ).on( 'widget-added', add_widget );
} );
}
else {
// We are in wp-admin -> Appearance -> Widgets
// Use proper condition and CODE if you want to target any page builder
// that doesn't use WP Core Widget Markup or Core JavaScript
$( window ).on( 'load', function() {
$( '#widgets-right div.widgets-sortables div.widget' ).each( function() {
modify_widget( 'non-customizer', $( this ) );
} );
$( document ).on( 'widget-added', modify_widget );
} );
}
$( document ).on( 'widget-updated', modify_widget );
})( window.wp, jQuery );
```
### Plugin Usage:
>
> ***Note:*** With the above sample Plugin CODE as it is, if you set the `title` of a Widget to `yes`, then it'll show *(mobile/desktop)* within the Widget Control UI heading, all the other Widget's will have *(desktop only)* in the Heading. In the customizer the change will be immediate, in `wp-admin -> widgets` the change will show after you `save` the changes. Of course you can change this behaviour by modifying the CODE (in JavaScript) to do the heading change for a different `field_name` or to only show that specific heading to some widgets and not to all of them.
>
>
>
For example, say you have a field named `use_mobile`, and you want to set the heading to *(mobile/desktop)* when it's set to `yes`. Then set the `compare` variable to something like:
```
var compare = {
field: 'use_mobile',
value: 'yes',
heading: ' <i>(mobile/desktop)</i> ',
alt_heading: ' <i>(desktop only)</i> ',
heading_selector: '.in-widget-title'
};
```
Also, if you want to change the entire heading (instead of just `.in-widget-title`), then you may change the `heading_selector` setting along with the correct markup for `heading` & `alt_heading` to do so. The possibilities are endless, but make sure WordPress core CODE doesn't produce any error if you want to be too much creative with the resulting markup.
Page builder integration:
-------------------------
Whether or not either of these solutions will work for a page builder will depend on that page builder implementation. If it uses WordPress supplied methods to load Widget Control UI then it should work without any modification, otherwise similar (but modified) implication may be possible for page builders as well. |
261,043 | <p>I am using <a href="https://en-ca.wordpress.org/plugins/custom-list-table-example/" rel="nofollow noreferrer">the Custom List Table Example plugin</a> as a basis to create my own custom list table. Everything is great, except one thorny point.</p>
<p>When I am processing bulk actions via the <code>process_bulk_action()</code> method, I would like to redirect using <code>wp_redirect()</code>. Here is an example:</p>
<pre><code>function process_bulk_action() {
// Some security check code here
// Get the bulk action
$action = $this->current_action();
if ($action == 'bulk_trash') {
// Code for the "delete process"
// Assuming "delete process" is successful
wp_redirect("http://url/path.php?update=1&message=some_message");
exit;
}
}
</code></pre>
<p>Please note, in the call <code>wp_redirect("http://url/path.php?update=1&message=some_message")</code>, I am trying to redirect to the same page that displays the list table in order to reload it with the result of the trash process. Also note that there is a <code>message</code> in the path that allows me to display a notification to the user regarding the result of the bulk action.</p>
<p>The problem is, I get an error message <code>Cannot modify header information - headers already sent by <file path></code>.</p>
<p>I understand what the message means, and the reasons behind it (the page is already loaded and cannot be redirected). However, how do I redirect then if I would like to do that after I process the bulk action? If redirect is not the correct solution, what other options do I have that allow me to re-load the custom <code>wp_list_table</code> again so that the listed records reflect items being deleted (i.e., less published items, and more items in trash)?</p>
<p>Thanks.</p>
| [
{
"answer_id": 272339,
"author": "Abhilash Narayan",
"author_id": 123210,
"author_profile": "https://wordpress.stackexchange.com/users/123210",
"pm_score": -1,
"selected": false,
"text": "<p>echo 'document.location=\"'<a href=\"http://url/path.php?update=1&message=some_message\" rel=... | 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/261043",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
] | I am using [the Custom List Table Example plugin](https://en-ca.wordpress.org/plugins/custom-list-table-example/) as a basis to create my own custom list table. Everything is great, except one thorny point.
When I am processing bulk actions via the `process_bulk_action()` method, I would like to redirect using `wp_redirect()`. Here is an example:
```
function process_bulk_action() {
// Some security check code here
// Get the bulk action
$action = $this->current_action();
if ($action == 'bulk_trash') {
// Code for the "delete process"
// Assuming "delete process" is successful
wp_redirect("http://url/path.php?update=1&message=some_message");
exit;
}
}
```
Please note, in the call `wp_redirect("http://url/path.php?update=1&message=some_message")`, I am trying to redirect to the same page that displays the list table in order to reload it with the result of the trash process. Also note that there is a `message` in the path that allows me to display a notification to the user regarding the result of the bulk action.
The problem is, I get an error message `Cannot modify header information - headers already sent by <file path>`.
I understand what the message means, and the reasons behind it (the page is already loaded and cannot be redirected). However, how do I redirect then if I would like to do that after I process the bulk action? If redirect is not the correct solution, what other options do I have that allow me to re-load the custom `wp_list_table` again so that the listed records reflect items being deleted (i.e., less published items, and more items in trash)?
Thanks. | Understand hierarchy, You don't need to redirect as form are posting values on same page.
```
function process_bulk_action() {
// Some security check code here
// Get the bulk action
$action = $this->current_action();
if ($action == 'bulk_trash') {
// Code for the "delete process"
$delete_ids = esc_sql($_POST['bulk-delete']);
//loop over the array of record ids
foreach($delete_ids as $id) {
self::delete_item($id);
}
// show admin notice
echo '<div class="notice notice-success is-dismissible"><p>Bulk Deleted..</p></div>';
}
}
```
another method is prepare\_items
```
public function prepare_items() {
// first check for action
$this->process_bulk_action();
// then code to render your view.
}
``` |
261,080 | <p>Does anyone know how I can get rid of index.php in my URL?
Right now if I add a new page, the address will be:</p>
<p>www.mywebsite.com/index.php/page1</p>
<p>But I want it to be:</p>
<p>wwww.mywebsite.com/page1</p>
<p>I surfed the web a lot! Changing the permalink doesn't work. Does anyone know how I can fix this?</p>
| [
{
"answer_id": 261081,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 3,
"selected": true,
"text": "<p>This is a classical case. All you need to do is to use Rewrite Rules. With Apache, you can do it in .htaccess:... | 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116068/"
] | Does anyone know how I can get rid of index.php in my URL?
Right now if I add a new page, the address will be:
www.mywebsite.com/index.php/page1
But I want it to be:
wwww.mywebsite.com/page1
I surfed the web a lot! Changing the permalink doesn't work. Does anyone know how I can fix this? | This is a classical case. All you need to do is to use Rewrite Rules. With Apache, you can do it in .htaccess:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
More on this in [codex](https://codex.wordpress.org/Using_Permalinks). |
261,090 | <p>I was wondering, how do I hide pages from my navbar? </p>
<p>I don't mean hide visibility to private nor do I want to remove the page from appearance -> menus -> MY_MENU (as I have custom CSS on one of the pages). </p>
<p><a href="https://i.stack.imgur.com/E6pJz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E6pJz.png" alt="My navigation bar"></a></p>
<p>just for reference, this is what my navbar looks like. </p>
<p><strong>CSS</strong></p>
<pre><code>.menu-item-346 a {
padding:1em;
text-align: center;
display:inline-block;
text-decoration: none !important;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-ms-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.menu-item-346 a:link, .menu-item-346 a:visited {
color:var(--white);
border:1px solid var(--white);
background:transparent;
}
.menu-item-346 a:hover, .menu-item-346 a:active {
color:var(--blue);
background:var(--white);
}
</code></pre>
| [
{
"answer_id": 261091,
"author": "pomaaa",
"author_id": 115755,
"author_profile": "https://wordpress.stackexchange.com/users/115755",
"pm_score": 0,
"selected": false,
"text": "<p>First you need to check the class of the item that you want to hide. If it's .menu-item-346, just add this t... | 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38839/"
] | I was wondering, how do I hide pages from my navbar?
I don't mean hide visibility to private nor do I want to remove the page from appearance -> menus -> MY\_MENU (as I have custom CSS on one of the pages).
[](https://i.stack.imgur.com/E6pJz.png)
just for reference, this is what my navbar looks like.
**CSS**
```
.menu-item-346 a {
padding:1em;
text-align: center;
display:inline-block;
text-decoration: none !important;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-ms-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.menu-item-346 a:link, .menu-item-346 a:visited {
color:var(--white);
border:1px solid var(--white);
background:transparent;
}
.menu-item-346 a:hover, .menu-item-346 a:active {
color:var(--blue);
background:var(--white);
}
``` | Instead of writing custom styles like `.menu-item-346` where you are hardcoding some styles...
why not just add a **custom css class** with the editor under `Appearance -> Menus`.
Wordpress has this build in.
Under `Appearance -> Menus` you need to open the `Screen Options` and tick the box `CSS Classes`.
After this you can now add one or multiple classes to every single menu-item.
You than could just write some custom CSS rules for these classes.
This way, your customer could just add these classes by himself. (or not) |
261,117 | <p>Devs</p>
<p>I have a WP-cronjob running that is supposed to import some pictures and set them as attachments for a specific post. But I'm apparently unable to do so while running it as a WP-cronjob - it works just fine when i run it on "init" for exampel. But as soon as i try to run it within a WP-cronjob it fails.</p>
<pre><code> register_activation_hook( __FILE__, 'OA_FeedManager_activated' );
function importpicture_activated()
{
if (! wp_next_scheduled( 'import_feed' ) )
{
wp_schedule_event( time(), 'hourly', 'import' );
}
}
add_action( 'import', 'call_import' );
function call_import()
{
//lots of code, where i get data from a XML feed, and creates a new post. no need to include it.
foreach($oDataXML->Media->Fotos->Foto as $key => $value)
{
$filename = wp_upload_dir()['path'].'/'.$oDataXML->SagsNr->__toString().'_'. $value->Checksum->__toString() . '.jpg';
$sPicture = $value->URL->__toString();
copy($sPicture, $filename);
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $iPost_ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
</code></pre>
<p>As I have been able to read, its because that the <code>wp_generate_attachment_metadata()</code> function is not currently included when doing a <code>wp-cronjob</code>, and I should <code>require_once('wp-load.php')</code>.</p>
<p>But sadly I'm not able to require that while running a cron job (I tried both <code>wp-load.php</code> & <code>wp-includes/post.php</code>) - but neither does the trick.</p>
<p>So maybe there is a wise man on WPSE that can enlighten me how I'm suppose to get my WP-cronjob running correctly.</p>
| [
{
"answer_id": 261124,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<p>At the top of your cronjob script (for example: <code>my-cron.php</code>), do this:</p>\n<pre><code>if ( ! de... | 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116092/"
] | Devs
I have a WP-cronjob running that is supposed to import some pictures and set them as attachments for a specific post. But I'm apparently unable to do so while running it as a WP-cronjob - it works just fine when i run it on "init" for exampel. But as soon as i try to run it within a WP-cronjob it fails.
```
register_activation_hook( __FILE__, 'OA_FeedManager_activated' );
function importpicture_activated()
{
if (! wp_next_scheduled( 'import_feed' ) )
{
wp_schedule_event( time(), 'hourly', 'import' );
}
}
add_action( 'import', 'call_import' );
function call_import()
{
//lots of code, where i get data from a XML feed, and creates a new post. no need to include it.
foreach($oDataXML->Media->Fotos->Foto as $key => $value)
{
$filename = wp_upload_dir()['path'].'/'.$oDataXML->SagsNr->__toString().'_'. $value->Checksum->__toString() . '.jpg';
$sPicture = $value->URL->__toString();
copy($sPicture, $filename);
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $iPost_ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
```
As I have been able to read, its because that the `wp_generate_attachment_metadata()` function is not currently included when doing a `wp-cronjob`, and I should `require_once('wp-load.php')`.
But sadly I'm not able to require that while running a cron job (I tried both `wp-load.php` & `wp-includes/post.php`) - but neither does the trick.
So maybe there is a wise man on WPSE that can enlighten me how I'm suppose to get my WP-cronjob running correctly. | Some of what is usually admin side functionality is not included as part of the "main" wordpress bootstrap, files containing uploaded file manipulation functions are one of them and you need to explicitly include them by adding
```
include_once( ABSPATH . 'wp-admin/includes/image.php' );
```
into your `call_import` function. |
261,123 | <p>I am trying to change the logo one specific page of this wordpress site. <a href="http://staging-domesticbliss.transitiongraphics.co.uk/db-home-help/" rel="nofollow noreferrer">http://staging-domesticbliss.transitiongraphics.co.uk/db-home-help/</a></p>
<p>Currently I know I am targeting the right page and element as I can hide the logo using:</p>
<pre><code>.page-id-6935 .w-logo-img > img {
display:none;
}
</code></pre>
<p>But how do I now show the logo located at <a href="http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png" rel="nofollow noreferrer">http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png</a></p>
<p>Thanks in advance</p>
| [
{
"answer_id": 261125,
"author": "Dan Knauss",
"author_id": 57078,
"author_profile": "https://wordpress.stackexchange.com/users/57078",
"pm_score": 0,
"selected": false,
"text": "<p>Logo settings are controlled through the WordPress customizer and administrator interface for most themes ... | 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261123",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116101/"
] | I am trying to change the logo one specific page of this wordpress site. <http://staging-domesticbliss.transitiongraphics.co.uk/db-home-help/>
Currently I know I am targeting the right page and element as I can hide the logo using:
```
.page-id-6935 .w-logo-img > img {
display:none;
}
```
But how do I now show the logo located at <http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png>
Thanks in advance | Rather than using the tag in html, set the logo using the CSS background property. Use background-image:url(<http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png>); instead. |
261,135 | <p>I would like to add a new menu item in the admin bar. So far, I have done the following:</p>
<pre><code>function add_book_menu_item ($wp_admin_bar) {
$args = array (
'id' => 'book',
'title' => 'Book',
'href' => 'http://example.com/',
'parent' => 'new-content'
);
$wp_admin_bar->add_node( $args );
}
add_action('admin_bar_menu', 'add_book_menu_item');
</code></pre>
<p>This is creating the <code>Book</code> menu item underneath the <code>+ New</code> menu (in the admin toolbar). However, the <code>Book</code> item comes in first (it is before the <code>Post</code> menu item). I would like it to appear between the <code>Media</code> and <code>Page</code> items. </p>
<p>The following image shows what I would like to do.</p>
<p><a href="https://i.stack.imgur.com/xTEut.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xTEut.png" alt="enter image description here"></a></p>
<p>How do I do that?</p>
<p>Thanks.</p>
| [
{
"answer_id": 261125,
"author": "Dan Knauss",
"author_id": 57078,
"author_profile": "https://wordpress.stackexchange.com/users/57078",
"pm_score": 0,
"selected": false,
"text": "<p>Logo settings are controlled through the WordPress customizer and administrator interface for most themes ... | 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
] | I would like to add a new menu item in the admin bar. So far, I have done the following:
```
function add_book_menu_item ($wp_admin_bar) {
$args = array (
'id' => 'book',
'title' => 'Book',
'href' => 'http://example.com/',
'parent' => 'new-content'
);
$wp_admin_bar->add_node( $args );
}
add_action('admin_bar_menu', 'add_book_menu_item');
```
This is creating the `Book` menu item underneath the `+ New` menu (in the admin toolbar). However, the `Book` item comes in first (it is before the `Post` menu item). I would like it to appear between the `Media` and `Page` items.
The following image shows what I would like to do.
[](https://i.stack.imgur.com/xTEut.png)
How do I do that?
Thanks. | Rather than using the tag in html, set the logo using the CSS background property. Use background-image:url(<http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png>); instead. |
261,137 | <p>I would like to replace a textarea in a wordpress plugin with the wp editor if possible.
Here is the textarea code:</p>
<pre><code><textarea id="<?php echo esc_attr( $html['id'] ); ?>" class="awpcp-textarea required" <?php echo $html['readonly'] ? 'readonly="readonly"' : ''; ?> name="<?php echo esc_attr( $html['name'] ); ?>" rows="10" cols="50" data-max-characters="<?php echo esc_attr( $characters_allowed ); ?>" data-remaining-characters="<?php echo esc_attr( $remaining_characters ); ?>"><?php /* Content alerady escaped if necessary. Do not escape again here! */ echo $value; ?></textarea>
</code></pre>
<p>I would appreciate anyone's help. I'm not a coder per se.
Thank you in advance for your help.</p>
<p>Pete</p>
| [
{
"answer_id": 261423,
"author": "Samyer",
"author_id": 112788,
"author_profile": "https://wordpress.stackexchange.com/users/112788",
"pm_score": 1,
"selected": false,
"text": "<p>You would need to edit the plugin and insert an instance of the wp_editor instead of that textarea.</p>\n\n<... | 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86094/"
] | I would like to replace a textarea in a wordpress plugin with the wp editor if possible.
Here is the textarea code:
```
<textarea id="<?php echo esc_attr( $html['id'] ); ?>" class="awpcp-textarea required" <?php echo $html['readonly'] ? 'readonly="readonly"' : ''; ?> name="<?php echo esc_attr( $html['name'] ); ?>" rows="10" cols="50" data-max-characters="<?php echo esc_attr( $characters_allowed ); ?>" data-remaining-characters="<?php echo esc_attr( $remaining_characters ); ?>"><?php /* Content alerady escaped if necessary. Do not escape again here! */ echo $value; ?></textarea>
```
I would appreciate anyone's help. I'm not a coder per se.
Thank you in advance for your help.
Pete | You would need to edit the plugin and insert an instance of the wp\_editor instead of that textarea.
Refer to [the wp\_editor function reference](https://codex.wordpress.org/Function_Reference/wp_editor). |
261,147 | <p>I wrote the following lines of code. It shows a dropdown menu with all available Wordpress categorys in the Wordpress customizer and can output the category slug. But instead of the slug I want to output the category id. Does anyone have an idea how to realize that?</p>
<pre><code>$categories = get_categories();
$cats = array();
$i = 0;
foreach($categories as $category){
if($i==0){
$default = $category->slug;
$i++;
}
$cats[$category->slug] = $category->name;
}
$wp_customize->add_setting('wptimes_homepage_featured_category', array(
'default' => $default
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'wptimes_homepage_featured_category', array(
'label' => 'Hervorgehobene Kategorie',
'description' => 'Wähle hier die Kategorie aus, die du auf der Startseite hervorheben möchtest.',
'section' => 'wptimes_homepage',
'settings' => 'wptimes_homepage_featured_category',
'type' => 'select',
'choices' => $cats
)));
</code></pre>
| [
{
"answer_id": 261242,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 1,
"selected": true,
"text": "<p>In your foreach loop just do a quick <code>print_r($category)</code> to see all available options.</p>\n\n<p>Th... | 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116113/"
] | I wrote the following lines of code. It shows a dropdown menu with all available Wordpress categorys in the Wordpress customizer and can output the category slug. But instead of the slug I want to output the category id. Does anyone have an idea how to realize that?
```
$categories = get_categories();
$cats = array();
$i = 0;
foreach($categories as $category){
if($i==0){
$default = $category->slug;
$i++;
}
$cats[$category->slug] = $category->name;
}
$wp_customize->add_setting('wptimes_homepage_featured_category', array(
'default' => $default
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'wptimes_homepage_featured_category', array(
'label' => 'Hervorgehobene Kategorie',
'description' => 'Wähle hier die Kategorie aus, die du auf der Startseite hervorheben möchtest.',
'section' => 'wptimes_homepage',
'settings' => 'wptimes_homepage_featured_category',
'type' => 'select',
'choices' => $cats
)));
``` | In your foreach loop just do a quick `print_r($category)` to see all available options.
Than you will see that you can use `$category->term_id` to get the `ID` of the term/category, instead of `$category->slug`.
So for example, by using your code from above:
```
$categories = get_categories();
$cats = array();
$i = 0;
foreach( $categories as $category ) {
// uncomment to see all $category data
#print_r($category);
if( $i == 0 ){
$default = $category->term_id;
$i++;
}
$cats[$category->term_id] = $category->name;
}
print_r($cats);
// Prints for example: Array ( [12] => Child-Cat [2] => Parent-Cat [1] => Uncategorized )
``` |
261,169 | <p>I have to create a shortcode so I can paste the shortcode inside the mobile menu plugin's options, the plugin doesn't accept PHP so I can't do <code><span class="header-cart-total"><?php echo edd_cart_total(); ?></span></code></p>
<p>The issue I'm having is echo'ing <code>edd_get_cart_total()</code> which causes a white screen on my website. I have to echo it or the cart total amount price doesn't show up fully-formatted. How do I echo it? This is in my functions.php file:</p>
<pre><code>function eddminicartfunc() {
return
'<div class="mobilemenucart">
<i class="fa fa-shopping-cart"></i>
<span class="header-cart-total"> ' . echo edd_get_cart_total() . ' </span>
<span class="header-cart edd-cart-quantity">
' . edd_get_cart_quantity() .'
</span>
</div>';
}
add_shortcode('eddminicart', 'eddminicartfunc');
</code></pre>
| [
{
"answer_id": 261171,
"author": "Sam",
"author_id": 115586,
"author_profile": "https://wordpress.stackexchange.com/users/115586",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure as to where you are trying to insert your code and what limits it has but try it like this and se... | 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261169",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49532/"
] | I have to create a shortcode so I can paste the shortcode inside the mobile menu plugin's options, the plugin doesn't accept PHP so I can't do `<span class="header-cart-total"><?php echo edd_cart_total(); ?></span>`
The issue I'm having is echo'ing `edd_get_cart_total()` which causes a white screen on my website. I have to echo it or the cart total amount price doesn't show up fully-formatted. How do I echo it? This is in my functions.php file:
```
function eddminicartfunc() {
return
'<div class="mobilemenucart">
<i class="fa fa-shopping-cart"></i>
<span class="header-cart-total"> ' . echo edd_get_cart_total() . ' </span>
<span class="header-cart edd-cart-quantity">
' . edd_get_cart_quantity() .'
</span>
</div>';
}
add_shortcode('eddminicart', 'eddminicartfunc');
``` | `echo` is a PHP language construct which pushes values to the output buffer. It does not have a return value, so concatenating it with a string would cause everything after the `echo` to immediately be sent to the output buffer, and everything prior to `echo` to compose the concatenated string. This is such a misuse of `echo` that PHP itself doesn't actually allow it - if you had WordPress debugging enabled you would see an error similar to
>
> Parse error: syntax error, unexpected 'echo' (T\_ECHO)
>
>
>
This error is what is causing your white screen - when not in debug mode, WordPress suppresses error output to avoid exposing potentially sensitive information to end-users.
You shouldn't use `echo` in shortcode logic, as internally WordPress does more processing with a shortcode's return value. So using `echo` in a shortcode has a good chance to mess up your final markup.
The inclusion of the `echo` before the `edd_get_cart_total()` does not result in currency formatting. I've dug through [the plugin in question's source code](https://github.com/easydigitaldownloads/easy-digital-downloads/blob/master/includes/cart/class-edd-cart.php#L1150) just to be sure. Rather, it's more likely that some function is hooked to the `edd_get_cart_total` filter to format the output in templates (thus formatting the total when you used it in your `header.php` template), however within the context of a shortcode that filter is not attached.
Conveniently, the plugin provides the `ebb_cart_total()` function which will always produce a currency-formatted total string. The first argument to the function is `$echo` which is true by default, and will cause the function to display the total instead of returning it - which, as detailed earlier, is not something you want to do in a shortcode - so set this argument to `false` to have the function return a string which you may concatenate with the rest of your shortcode markup.
All together:
```
function eddminicartfunc() {
return
'<div class="mobilemenucart">
<i class="fa fa-shopping-cart"></i>
<span class="header-cart-total"> ' . edd_cart_total( false ) . ' </span>
<span class="header-cart edd-cart-quantity">' . edd_get_cart_quantity() . '</span>
</div>';
}
add_shortcode( 'eddminicart', 'eddminicartfunc' );
``` |
261,177 | <p>Following the <a href="https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/" rel="nofollow noreferrer">Wordpress documentation about the Rest Api</a>, i can manage to make an ajax POST working, but only when logged in to Wordpress. Here are the basic files shown in the documentation:</p>
<h3>functions.php</h3>
<pre><code>wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );
</code></pre>
<h3>app.js</h3>
<pre><code>$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
</code></pre>
<p>I'm showing this example as it is presented as an easy one, but is <strong>not working</strong> when not logged in. It is always giving me a 401 Unauthorized response / “rest_cannot_create”...</p>
<p>Any tip ?</p>
<p>Thank you !</p>
| [
{
"answer_id": 261185,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>The </p>\n\n<blockquote>\n <p>the_author()</p>\n</blockquote>\n\n<p>function should return the name o... | 2017/03/24 | [
"https://wordpress.stackexchange.com/questions/261177",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102982/"
] | Following the [Wordpress documentation about the Rest Api](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/), i can manage to make an ajax POST working, but only when logged in to Wordpress. Here are the basic files shown in the documentation:
### functions.php
```
wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );
```
### app.js
```
$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
```
I'm showing this example as it is presented as an easy one, but is **not working** when not logged in. It is always giving me a 401 Unauthorized response / “rest\_cannot\_create”...
Any tip ?
Thank you ! | Here are three possible approaches:
1. A normal WP installation already has [custom fields](https://codex.wordpress.org/Custom_Fields) which you can add to your post. So you could use those to add the original author's name to. The only problem is that general themes usually do not display `the_meta`, because they do not know what to expect. In your case you would want to replace `the_author` in your theme with `the_meta` (don't mess with the original theme files, use a child theme!)
2. Easier, but a bit hacky: add the original authors to the user list. They don't need to know they have an account, just provide bogus e-mail addresses and don't let WP send their password to them. Now you can simply assign them as authors and they will have their own author page as well.
3. The most thorough approach is [adding a meta box](https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes) yourself (or use a [plugin like WCK](https://ido.wordpress.org/plugins-wp/wck-custom-fields-and-custom-post-types-creator/)). This gives you complete control on how to insert the information in your child theme. |
261,196 | <p>After months of leaving and deleting my WordPress site, I decided to try again. I downloaded the new version 4.7.3, installed and added a new post. So far so good. </p>
<p>I then went back to edit the post and the same error that I received before, cannot find the post; nothing to see here, message.</p>
<p>I cannot edit any new post that I create, but I can create a new post. The odd things are that I can modify the default message that is created on install by WordPress.</p>
<p>I deleted the database and the entire home directory multiple times. Deleted the .htaccess file and changed permalinks to no avail as well.</p>
<p>The setup is a fresh install with no plugins, no themes used except default. I tried switching between the different default also. Still, no dice.</p>
<p>Whenever I click the update, it returns a 404 error, page not found, as stated by Firefox dev tool. Add new does work. If I cick to edit a new post, it bring the page up in the editor. But as soon as I click update, 404 error.</p>
<p>This is the contents of the .htaccess file as by WordPress.</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p><strong>Update</strong></p>
<p>I just noticed in one of the logs this error when I changed the permalink to plain. [Fri Mar 24 06:15:46 2017] [error] [client xxxxxxxx] File does not exist: /home/domain/public_html/403.shtml, referer: domain.com/wp-admin/post.php?post=14&action=edit</p>
<p>Any ideas?</p>
| [
{
"answer_id": 261210,
"author": "Self Designs",
"author_id": 75780,
"author_profile": "https://wordpress.stackexchange.com/users/75780",
"pm_score": 0,
"selected": false,
"text": "<p>You could try to reset the WordPress permalinks to see if this is causing the 404 error. Here is a usefu... | 2017/03/24 | [
"https://wordpress.stackexchange.com/questions/261196",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116145/"
] | After months of leaving and deleting my WordPress site, I decided to try again. I downloaded the new version 4.7.3, installed and added a new post. So far so good.
I then went back to edit the post and the same error that I received before, cannot find the post; nothing to see here, message.
I cannot edit any new post that I create, but I can create a new post. The odd things are that I can modify the default message that is created on install by WordPress.
I deleted the database and the entire home directory multiple times. Deleted the .htaccess file and changed permalinks to no avail as well.
The setup is a fresh install with no plugins, no themes used except default. I tried switching between the different default also. Still, no dice.
Whenever I click the update, it returns a 404 error, page not found, as stated by Firefox dev tool. Add new does work. If I cick to edit a new post, it bring the page up in the editor. But as soon as I click update, 404 error.
This is the contents of the .htaccess file as by WordPress.
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
**Update**
I just noticed in one of the logs this error when I changed the permalink to plain. [Fri Mar 24 06:15:46 2017] [error] [client xxxxxxxx] File does not exist: /home/domain/public\_html/403.shtml, referer: domain.com/wp-admin/post.php?post=14&action=edit
Any ideas? | To do so .. You need to login to wordpress admin and then need to save the permalink again..
Just go to Settings >> Permalink
And save without doing any changes.. and that error should be gone.. |
261,226 | <p>I'm using ACF to display a class within a <code><header></code> tag. The code for this sits within header.php. The custom field appears across all page templates in WP admin. Here's how it's working on the front-end: </p>
<pre><code><header
class="site-header
<?php
$header = get_field( 'header',$post->ID );
if ($header) {
echo esc_attr( $header );
}
else {
echo 'white';
}
?>"
>
</code></pre>
<p>This works perfectly on all pages apart from the 404. I'm receiving the following message within dev tools: </p>
<pre><code><header class="site-header <br /> <b>Notice</b>: Trying to get property of non-object in <b>/Applications/MAMP/htdocs/theme/wp-content/themes/theme/header.php</b> on line <b>28</b><br /> white">
</header>
</code></pre>
<p>This is happening because the 404 is a static page / post and does not have an ID associated to it.</p>
<p>Is there a function within WordPress I can use to display my custom field properly?</p>
| [
{
"answer_id": 261210,
"author": "Self Designs",
"author_id": 75780,
"author_profile": "https://wordpress.stackexchange.com/users/75780",
"pm_score": 0,
"selected": false,
"text": "<p>You could try to reset the WordPress permalinks to see if this is causing the 404 error. Here is a usefu... | 2017/03/24 | [
"https://wordpress.stackexchange.com/questions/261226",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
] | I'm using ACF to display a class within a `<header>` tag. The code for this sits within header.php. The custom field appears across all page templates in WP admin. Here's how it's working on the front-end:
```
<header
class="site-header
<?php
$header = get_field( 'header',$post->ID );
if ($header) {
echo esc_attr( $header );
}
else {
echo 'white';
}
?>"
>
```
This works perfectly on all pages apart from the 404. I'm receiving the following message within dev tools:
```
<header class="site-header <br /> <b>Notice</b>: Trying to get property of non-object in <b>/Applications/MAMP/htdocs/theme/wp-content/themes/theme/header.php</b> on line <b>28</b><br /> white">
</header>
```
This is happening because the 404 is a static page / post and does not have an ID associated to it.
Is there a function within WordPress I can use to display my custom field properly? | To do so .. You need to login to wordpress admin and then need to save the permalink again..
Just go to Settings >> Permalink
And save without doing any changes.. and that error should be gone.. |
261,293 | <p>I added the possibility to register on my site (with the role of subscriber), however each registration creates an author page for the user, but I do not want these pages to be indexed, only the pages of authors with roles above.</p>
<p>Something like the code below, but theres no get_user_role function, so i do not know how to get to that result. I would be grateful if anyone could help.</p>
<pre><code><meta name="robots" content="<?php if( is_page('author') ) && get_user_role('subscriber'); {
echo "noindex, nofollow";
}else{
echo "index, follow";
} ?>" />
</code></pre>
<p>Edit:</p>
<p>This is the code of @belinos answer. I put it inside header.php, the problem is that an error appears on the <a href="http://gamersaction.pe.hu/" rel="nofollow noreferrer">online site</a>, on localhost it does not appear.</p>
<pre><code><?php $curauth = ( isset( $_GET[ 'author_name' ] ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval ($author ) );
$auth_data = get_userdata( $curauth->ID );
if ( in_array( 'subscriber', $auth_data->roles )) { ?>
<meta name="robots" content="noindex, nofollow"/>
<?php } else { ?>
<meta name="robots" content="index, follow"/>
<?php } ?>
</code></pre>
<p>This is the error:</p>
<p>Warning: in_array() expects parameter 2 to be array, null given in /home/u836053643/public_html/wp-content/themes/gamersaction/header.php on line 35</p>
<p>And that is the line 35:</p>
<pre><code>if ( in_array( 'subscriber', $auth_data->roles )) { ?>
</code></pre>
<p>The code works perfectly but is showing this error.</p>
| [
{
"answer_id": 261300,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 1,
"selected": false,
"text": "<p>The function you want is <code>get_userdata()</code>. Since you need to do this outside the loop, the process i... | 2017/03/24 | [
"https://wordpress.stackexchange.com/questions/261293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
] | I added the possibility to register on my site (with the role of subscriber), however each registration creates an author page for the user, but I do not want these pages to be indexed, only the pages of authors with roles above.
Something like the code below, but theres no get\_user\_role function, so i do not know how to get to that result. I would be grateful if anyone could help.
```
<meta name="robots" content="<?php if( is_page('author') ) && get_user_role('subscriber'); {
echo "noindex, nofollow";
}else{
echo "index, follow";
} ?>" />
```
Edit:
This is the code of @belinos answer. I put it inside header.php, the problem is that an error appears on the [online site](http://gamersaction.pe.hu/), on localhost it does not appear.
```
<?php $curauth = ( isset( $_GET[ 'author_name' ] ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval ($author ) );
$auth_data = get_userdata( $curauth->ID );
if ( in_array( 'subscriber', $auth_data->roles )) { ?>
<meta name="robots" content="noindex, nofollow"/>
<?php } else { ?>
<meta name="robots" content="index, follow"/>
<?php } ?>
```
This is the error:
Warning: in\_array() expects parameter 2 to be array, null given in /home/u836053643/public\_html/wp-content/themes/gamersaction/header.php on line 35
And that is the line 35:
```
if ( in_array( 'subscriber', $auth_data->roles )) { ?>
```
The code works perfectly but is showing this error. | The function you want is `get_userdata()`. Since you need to do this outside the loop, the process is a little less straight-forward.
The first thing you need to do is set up a variable called `$curauth` which is an object that you create by accessing the database by using the `$_GET[]` superglobal.
```
$curauth = ( isset( $_GET[ 'author_name' ] ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval ($author ) );
```
This assigning of `$curauth` must be in your `author.php` file.
After that, we can then use the `get_userdata()` function and feed it the ID from `$curauth`.
```
$auth_data = get_userdata( $curauth->ID );
```
And from there your conditional becomes:
```
if ( in_array( 'subscriber', $auth_data->roles ) ) {
// No Follow Code
} else {
// Follow Code
}
```
My advice would be to make this all a function in your `functions.php` file:
```
function author_nofollow( $author ) {
$auth_id = $author->ID;
$auth_data = get_userdata( $auth_id );
if ( in_array( 'subscriber', $auth_data->roles ) ) {
echo 'noindex, nofollow';
} else {
echo 'index, follow';
}
}
```
Then you would just call it like this:
```
<meta name="robots" content="<?php author_nofollow( $curauth ); ?>">
``` |