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 |
|---|---|---|---|---|---|---|
247,018 | <p>I use the <code>WP_Customize_Image_Control</code> to add the image.</p>
<p>But, The <code>default</code> value is accessible in <code>Customizer</code> only!!!
On front-end It return <code>empty</code>.</p>
<h3>How to reproduce?</h3>
<p>Copy below code snippet and paste in your themes <code>functions.php</code>.</p>
<p>Visit URL <code>http://YOUR_SITE/wp-admin/customize.php?autofocus[section]=section-test_option</code> to open section <code>Test Section</code></p>
<pre><code>add_action( 'customize_register', 'test_1234_customize_register' );
add_action( 'wp_head', 'test_1234_customizer_ouput_debug' );
function test_1234_customizer_ouput_debug() {
// $options = get_theme_mod( 'this-is-the-test-option' );
$options = get_option( 'this-is-the-test-option' );
echo '<pre style="background: #fff;">Default Image URL: ';
print_r( $options );
echo '</pre>';
}
function test_1234_customize_register( $wp_customize ) {
/**
* Test Section
*/
$wp_customize->add_section( 'section-test_option', array(
'title' => __( 'Test Option', 'next' ),
) );
/**
* Test Option - 1
*/
$wp_customize->add_setting( 'this-is-the-test-option', array(
'default' => 'https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
'type' => 'option', // Comment this parameter to use 'get_theme_mod'
) );
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'this-is-the-test-option', array(
'section' => 'section-test_option',
'label' => __( 'Test', 'next' ),
'settings' => 'this-is-the-test-option',
'library_filter' => array( 'gif', 'jpg', 'jpeg', 'png', 'ico' ),
) ) );
}
</code></pre>
<hr />
<h3>Output</h3>
<ol>
<li>In Customizer window preview</li>
</ol>
<p><a href="http://bsf.io/net4f" rel="nofollow noreferrer">http://bsf.io/net4f</a></p>
<ol start="2">
<li>In Front End ( Checked in Incognito window too )</li>
</ol>
<p><a href="http://bsf.io/u59cm" rel="nofollow noreferrer">http://bsf.io/u59cm</a></p>
<hr />
<p>As per above example I'm able to use:
<code>get_option( 'this-is-the-test-option', 'https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png' )</code> to get default image.</p>
<p>But, It'll be fail if I store the options in array. E.g.</p>
<pre><code>$wp_customize->add_setting( 'this-is-the-test-option[option1]', array(
...
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'this-is-the-test-option[option1]', array(
...
</code></pre>
<p>In above situation the best solution is merging the default values. I found the solution suggested by @westonruter in <a href="https://gist.github.com/westonruter/c9b9cf597e9e9129070d67b68920168e/9d9a4d8f0a751b549dff17c34f4790568316d8ac#file-functions-php-L37" rel="nofollow noreferrer">gist</a>.</p>
<hr />
<p>But, Questions are:</p>
<ol>
<li>Why the default value is accessible in <code>Customizer Preview window</code>? ( As per the above code snippet.)</li>
<li>Is <code>default</code> parameter for the control <code>WP_Customize_Image_Control</code> is useful?</li>
</ol>
| [
{
"answer_id": 247046,
"author": "Felipe Rodrigues",
"author_id": 104101,
"author_profile": "https://wordpress.stackexchange.com/users/104101",
"pm_score": 1,
"selected": false,
"text": "<p>The default value that you set on the image <code>add_setting</code> will only be applyed if there... | 2016/11/22 | [
"https://wordpress.stackexchange.com/questions/247018",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52167/"
] | I use the `WP_Customize_Image_Control` to add the image.
But, The `default` value is accessible in `Customizer` only!!!
On front-end It return `empty`.
### How to reproduce?
Copy below code snippet and paste in your themes `functions.php`.
Visit URL `http://YOUR_SITE/wp-admin/customize.php?autofocus[section]=section-test_option` to open section `Test Section`
```
add_action( 'customize_register', 'test_1234_customize_register' );
add_action( 'wp_head', 'test_1234_customizer_ouput_debug' );
function test_1234_customizer_ouput_debug() {
// $options = get_theme_mod( 'this-is-the-test-option' );
$options = get_option( 'this-is-the-test-option' );
echo '<pre style="background: #fff;">Default Image URL: ';
print_r( $options );
echo '</pre>';
}
function test_1234_customize_register( $wp_customize ) {
/**
* Test Section
*/
$wp_customize->add_section( 'section-test_option', array(
'title' => __( 'Test Option', 'next' ),
) );
/**
* Test Option - 1
*/
$wp_customize->add_setting( 'this-is-the-test-option', array(
'default' => 'https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
'type' => 'option', // Comment this parameter to use 'get_theme_mod'
) );
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'this-is-the-test-option', array(
'section' => 'section-test_option',
'label' => __( 'Test', 'next' ),
'settings' => 'this-is-the-test-option',
'library_filter' => array( 'gif', 'jpg', 'jpeg', 'png', 'ico' ),
) ) );
}
```
---
### Output
1. In Customizer window preview
<http://bsf.io/net4f>
2. In Front End ( Checked in Incognito window too )
<http://bsf.io/u59cm>
---
As per above example I'm able to use:
`get_option( 'this-is-the-test-option', 'https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png' )` to get default image.
But, It'll be fail if I store the options in array. E.g.
```
$wp_customize->add_setting( 'this-is-the-test-option[option1]', array(
...
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'this-is-the-test-option[option1]', array(
...
```
In above situation the best solution is merging the default values. I found the solution suggested by @westonruter in [gist](https://gist.github.com/westonruter/c9b9cf597e9e9129070d67b68920168e/9d9a4d8f0a751b549dff17c34f4790568316d8ac#file-functions-php-L37).
---
But, Questions are:
1. Why the default value is accessible in `Customizer Preview window`? ( As per the above code snippet.)
2. Is `default` parameter for the control `WP_Customize_Image_Control` is useful? | The default value that you set on the image `add_setting` will only be applyed if there is a any option called 'reset to default' on the image control. This argument will not output any default value to the page.
The second argument of the function `get_option( 'option_name', $default )`. The `$default` parameter **will not submit anything to the DB**. It only returned if the option does not exists. e.g: when the user installed the theme, and the logo (or the option that displays anything on the page) must not be empty. But if he save the option, the option will exist on the db, even if empty. Then this default will not apply anymore. it works like a place holder.
If you want a default value, even if the option are saved and return a empty string, you can do this:
```
$option = get_option( 'option_name', $default )
echo ( empty( $option ) ? 'default' : $option );
```
The empty() function will check if the returned value are a empty string, or anything that represents a empty (boolean, integer, null, etc). You can read more here: <http://php.net/manual/pt_BR/function.empty.php>
This way, a default value will be ever applyed, if the option exists.
>
> Note: its a best practice to use `'type' => 'theme_mod'` when creating mods for themes, not `'type' => 'option'`. If you omit this
> arg, the default will be theme\_mod.
>
>
> |
247,023 | <p>If I have a front-end post form where a user enters a url, is it OK and recommended to use <code>esc_url()</code> twice - once for cleaning the input before using <code>update_post_meta</code> for database storage, and again on output.</p>
<pre><code>// escape url before using update_post_meta
update_post_meta( $post_id, 'url', esc_url( $url ) );
// escape url on output
echo esc_url( get_post_meta( $post_id, 'url', true ) );
</code></pre>
<p>Any help appreciated.</p>
| [
{
"answer_id": 247025,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 1,
"selected": false,
"text": "<p>According to the Wordpress codex, it appears it would be better to pass the first URL using <a href=\"https:/... | 2016/11/22 | [
"https://wordpress.stackexchange.com/questions/247023",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88767/"
] | If I have a front-end post form where a user enters a url, is it OK and recommended to use `esc_url()` twice - once for cleaning the input before using `update_post_meta` for database storage, and again on output.
```
// escape url before using update_post_meta
update_post_meta( $post_id, 'url', esc_url( $url ) );
// escape url on output
echo esc_url( get_post_meta( $post_id, 'url', true ) );
```
Any help appreciated. | It's okay to use it more than once, but not encouraged. However, in your first example, you're saving the URL to the database. When you do that, or when using the URL in the `wp_remote_*` context, or a redirect, or any other non-display context, you should be using `esc_url_raw()` instead.
Also note that `get_post_meta` will return an array, unless the third argument `$single` is set to true. If you're dealing with a single key-value pair you'll want:
```
echo esc_url( get_post_meta( $post_id, 'url', true ) );
```
Hope that helps! |
247,040 | <p>I am trying to query some wordpress posts, they have a custom post status of <code>closed</code>.</p>
<p>When I run this query, they get returned despite their custom status being set to <code>closed</code>, even though I've asked for <code>published</code>:</p>
<pre><code>$now = strtotime(date('d.m.Y H:i:s'));
$args = array(
'post_type' => 'vacancy',
'post_status' => 'published',
'posts_per_page' => 1000,
'orderby' => 'meta_value_num',
'meta_key' => 'wpcf-closing-date',
'meta_query' => array(
array(
'key' => 'wpcf-closing-date',
'value' => $now,
'compare' => '<=',
)
),
);
$vacancies = new WP_Query($args);
</code></pre>
<p>I would have expected that only posts with the <code>post_status</code> of <code>published</code> would have come back. Anybody any ideas why this is returning <code>closed</code> posts?</p>
| [
{
"answer_id": 247042,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": -1,
"selected": false,
"text": "<p>The post_status <code>closed</code> is not part of the default post_status.</p>\n\n<p>This custom post status... | 2016/11/22 | [
"https://wordpress.stackexchange.com/questions/247040",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27357/"
] | I am trying to query some wordpress posts, they have a custom post status of `closed`.
When I run this query, they get returned despite their custom status being set to `closed`, even though I've asked for `published`:
```
$now = strtotime(date('d.m.Y H:i:s'));
$args = array(
'post_type' => 'vacancy',
'post_status' => 'published',
'posts_per_page' => 1000,
'orderby' => 'meta_value_num',
'meta_key' => 'wpcf-closing-date',
'meta_query' => array(
array(
'key' => 'wpcf-closing-date',
'value' => $now,
'compare' => '<=',
)
),
);
$vacancies = new WP_Query($args);
```
I would have expected that only posts with the `post_status` of `published` would have come back. Anybody any ideas why this is returning `closed` posts? | The correct [`post_status`](https://codex.wordpress.org/Class_Reference/WP_Query#Status_Parameters) for a 'published' post is 'publish':
```
'post_status' => 'publish',
``` |
247,041 | <p>Currently, wordpress default is returning 200 on either failed or successfull login attempt.
The modern standard, used by all web application framework is to return 401 (or 403) on failed login attempts.</p>
<p>This allows third party tools (think waf, fail2ban, etc) to detect brute forcing attempt and block it from outside of wordpress.</p>
<p>I can't find where I can make this change or is there a plugin providing such a functionality.</p>
<p>Yes, I'm well aware of plugins who attempt to provide "brute force blocking" from inside of Wordpress. But besides being a problem on their own, they are prone to being shut from inside the Wordpress installation. And the defence is placed in the <strong>wrong</strong> level. Instead of being a perimeter defense, all those requests hit the actual wordpress Installation. So no, this isn't a good option for me.</p>
<p>Thanks for the help!</p>
| [
{
"answer_id": 247331,
"author": "Amit Rahav",
"author_id": 30989,
"author_profile": "https://wordpress.stackexchange.com/users/30989",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress handles login failed in two ways:</p>\n\n<ol>\n<li><p>If it is a bad credential, and both userna... | 2016/11/22 | [
"https://wordpress.stackexchange.com/questions/247041",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6129/"
] | Currently, wordpress default is returning 200 on either failed or successfull login attempt.
The modern standard, used by all web application framework is to return 401 (or 403) on failed login attempts.
This allows third party tools (think waf, fail2ban, etc) to detect brute forcing attempt and block it from outside of wordpress.
I can't find where I can make this change or is there a plugin providing such a functionality.
Yes, I'm well aware of plugins who attempt to provide "brute force blocking" from inside of Wordpress. But besides being a problem on their own, they are prone to being shut from inside the Wordpress installation. And the defence is placed in the **wrong** level. Instead of being a perimeter defense, all those requests hit the actual wordpress Installation. So no, this isn't a good option for me.
Thanks for the help! | WordPress handles login failed in two ways:
1. If it is a bad credential, and both username and password have a value, then this action can be captured by wp\_login\_failed
2. If both, or one, of the options are empty, then WordPress generates the error object as the first parameter in the authenticate filter; it does not open and wp\_login\_failed action captures this cause/event For what we have done here,
see comments in code:
```
add_filter( 'authenticate', function( $user, $username, $password ) {
// forcefully capture login failed to forcefully open wp_login_failed action,
// so that this event can be captured
if ( empty( $username ) || empty( $password ) ) {
do_action( 'wp_login_failed', $user );
}
return $user;
} );
// to handle even you can handle the error like
add_action( 'wp_login_failed', function( $username ) {
if ( is_wp_error( $username ) ) {
// you return 401 with wp function, this action takes place before header sent.
$wp_query->set_401();
status_header( 401 );
nocache_headers();
}
} );
```
my answer is a combination of : [Redirect user using the 'wp\_login\_failed' action hook if the error is 'empty\_username' or 'empty\_password'](https://wordpress.stackexchange.com/questions/172608/redirect-user-using-the-wp-login-failed-action-hook-if-the-error-is-empty-use) and [How to force a 404 on WordPress](https://wordpress.stackexchange.com/questions/91900/how-to-force-a-404-on-wordpress)
**update:** I wrote super simple plugin to do this [WP-401-On-Failed-Login](https://github.com/amitrahav/WP-401-On-Failed-Login). It uses some wp auth hooks, and set\_header() before content being sent. |
247,056 | <p>How do I find out the correct hooks that are being used when installed plugins and themes insert their own menus into the WordPress admin top menu bar?</p>
<p>I know how to remove them from the admin sidebar from the following the instructions in the following post </p>
<p><a href="https://wordpress.stackexchange.com/questions/136058/how-to-remove-admin-menu-pages-inserted-by-plugins">How to remove admin menu pages inserted by plugins?</a></p>
<p>but it doesn't explain how to find the ones when they're inserted into the top admin bar. I'm specifically wanting to remove the Avada link from the top admin menu bar if anyone can help.</p>
| [
{
"answer_id": 247061,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>You can play around the <code>WP_Admin_Bar</code> class</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'modif... | 2016/11/22 | [
"https://wordpress.stackexchange.com/questions/247056",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105345/"
] | How do I find out the correct hooks that are being used when installed plugins and themes insert their own menus into the WordPress admin top menu bar?
I know how to remove them from the admin sidebar from the following the instructions in the following post
[How to remove admin menu pages inserted by plugins?](https://wordpress.stackexchange.com/questions/136058/how-to-remove-admin-menu-pages-inserted-by-plugins)
but it doesn't explain how to find the ones when they're inserted into the top admin bar. I'm specifically wanting to remove the Avada link from the top admin menu bar if anyone can help. | You can play around the `WP_Admin_Bar` class
```
add_action( 'admin_bar_menu', 'modify_admin_bar' );
function modify_admin_bar( $wp_admin_bar ){
// do something with $wp_admin_bar;
$wp_admin_bar->get_nodes();
}
```
Have look to the codex [WP\_Admin\_Bar](https://codex.wordpress.org/Class_Reference/WP_Admin_Bar) to see all methods available. |
247,067 | <p>I'm using groupblog feature and hence multisite is required with it .</p>
<p>If a new user(not logged in) reaches any of the groupblog directly viz. a subsite and clicks the login button he's redirected to www.mainsite.com/subsite/wp-login.php whereas i want him to reach at www.mainsite.com/wp-login.php .
How can i do this ?</p>
| [
{
"answer_id": 247061,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>You can play around the <code>WP_Admin_Bar</code> class</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'modif... | 2016/11/22 | [
"https://wordpress.stackexchange.com/questions/247067",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107529/"
] | I'm using groupblog feature and hence multisite is required with it .
If a new user(not logged in) reaches any of the groupblog directly viz. a subsite and clicks the login button he's redirected to www.mainsite.com/subsite/wp-login.php whereas i want him to reach at www.mainsite.com/wp-login.php .
How can i do this ? | You can play around the `WP_Admin_Bar` class
```
add_action( 'admin_bar_menu', 'modify_admin_bar' );
function modify_admin_bar( $wp_admin_bar ){
// do something with $wp_admin_bar;
$wp_admin_bar->get_nodes();
}
```
Have look to the codex [WP\_Admin\_Bar](https://codex.wordpress.org/Class_Reference/WP_Admin_Bar) to see all methods available. |
247,083 | <p>I've defined a variable in my child theme header.php.</p>
<p>I'd like to get the value of this variable from one of the templates that is rendered after the request in which the header.php is called.</p>
<p>So, in header I've got this:</p>
<pre><code>$foo = "bar"
</code></pre>
<p>If I test for this value with header.php, it returns "bar".
But if I test for the value from a template called after the header gets called, I get 'null'.</p>
<p>The first thing I tried was putting 'global $foo' before the definition of $foo. But this didn't change my result.</p>
| [
{
"answer_id": 247084,
"author": "JHoffmann",
"author_id": 63847,
"author_profile": "https://wordpress.stackexchange.com/users/63847",
"pm_score": -1,
"selected": true,
"text": "<p>It the template is called via <code>get_template_part()</code>, then it is in a new variable scope. to acce... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51378/"
] | I've defined a variable in my child theme header.php.
I'd like to get the value of this variable from one of the templates that is rendered after the request in which the header.php is called.
So, in header I've got this:
```
$foo = "bar"
```
If I test for this value with header.php, it returns "bar".
But if I test for the value from a template called after the header gets called, I get 'null'.
The first thing I tried was putting 'global $foo' before the definition of $foo. But this didn't change my result. | It the template is called via `get_template_part()`, then it is in a new variable scope. to access it, you have to use the `global` keyword in you template file:
```
global $foo;
echo $foo;
```
As `header.php` probalbly is also called in a function scope, you have to make sure there the variable is used in global scope when definig it:
```
global $foo;
$foo = 'bar';
``` |
247,102 | <p>I have a front-end form and I'm using a POST handler in a plugin using the init hook. Basically, it's:</p>
<pre><code><form action="" method="POST" id="mktinto-form" class="profile-form">
<!-- form fields here -->
<input type="hidden" name="action" value="profile-form">
<input type="submit" value="Submit">
</form>
</code></pre>
<p>And the handler:</p>
<pre><code>function vv_process_profile_forms() {
if ( isset( $_POST['action'] ) && $_POST['action'] == 'profile-form' ) {
// form processing code here
$redirect_page = get_permalink( 586 );
wp_redirect( $redirect_page ); exit;
}
}
add_action( 'init','vv_process_profile_forms' );
</code></pre>
<p>The form is submitted and the page redirects to the next page in the process.</p>
<p>The form posts fine, the redirect happens, but the form handler actually runs twice. If I remove the redirect, it only runs once, like it should, but then, of course, it doesn't move to the next page. So it seems like the double posting is a result of the redirect, but I have no idea why. </p>
| [
{
"answer_id": 247104,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 0,
"selected": false,
"text": "<p>You can fix it through Session. try</p>\n\n<pre><code>function vv_process_profile_forms() {\n session_start();... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247102",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107550/"
] | I have a front-end form and I'm using a POST handler in a plugin using the init hook. Basically, it's:
```
<form action="" method="POST" id="mktinto-form" class="profile-form">
<!-- form fields here -->
<input type="hidden" name="action" value="profile-form">
<input type="submit" value="Submit">
</form>
```
And the handler:
```
function vv_process_profile_forms() {
if ( isset( $_POST['action'] ) && $_POST['action'] == 'profile-form' ) {
// form processing code here
$redirect_page = get_permalink( 586 );
wp_redirect( $redirect_page ); exit;
}
}
add_action( 'init','vv_process_profile_forms' );
```
The form is submitted and the page redirects to the next page in the process.
The form posts fine, the redirect happens, but the form handler actually runs twice. If I remove the redirect, it only runs once, like it should, but then, of course, it doesn't move to the next page. So it seems like the double posting is a result of the redirect, but I have no idea why. | I meant to answer this earlier. Turns out the problem was developer error (me!). I was using a javascript form handler that would process data and pass it on to the php form handler. Turns out that I was actually loading the .js file twice on the page. Kicked myself real hard for wasting the better part of a day figuring that out.
I had actually fixed it by unbinding the form submit event in the javascript, but then I found the root cause and no longer needed to do that. |
247,109 | <h2>Question:</h2>
<p>Where is the <em>proper</em> WordPress place to add a filter for <code>pre_get_table_charset</code>, prior to it getting executed?</p>
<p>The <code>pre_get_table_charset</code> filter is triggered in <code>wp-db.php::get_table_charset()</code>.</p>
<hr>
<p><strong>Update: Solution</strong></p>
<p>Mark Kaplun pointed me in the right direction, which is to put the filter into a drop-in. Because we're using an MU setup (as evidenced by my table-name), the easiest and simplest drop-in was <code>sunrise.php</code>, which as I understand it, is designed to be loaded super-early anyway.</p>
<p><strong>Update: Caveat</strong></p>
<p>Once you successfully have the filter loaded, you will start getting these errors:</p>
<pre><code>PHP Notice: Undefined index: wp_2_options in /srv/www/wordpress/web/wp/wp-includes/wp-db.php on line 25xx
</code></pre>
<p>This is because wp-db.php doesn't cache the result the same way it would if it had to look it up from the DB, and this cache is used by both <code>wp-db.php::get_table_charset()</code> and and <code>wp-db.php::get_col_charset()</code>.</p>
<p><strong>Solution:</strong> define a second filter, <code>pre_get_col_charset</code>, with 3 parameters, which returns the same value as your <code>pre_get_table_charset</code> filter.</p>
<pre><code>add_filter('pre_get_col_charset', function($charset, $table, $column) {
return 'utf8mb4';
}, 10, 2);
</code></pre>
<hr>
<h2><strong>Background:</strong></h2>
<p>WordPress generates a consistently slow query on our server: </p>
<pre><code>SHOW FULL COLUMNS FROM `wp_2_options`
</code></pre>
<p>This is generated in <code>wp-db.php::get_table_charset()</code>, and is used to determine the charset for a table. It is, of course, entirely unnecessary, because we <em>know</em> what the charset is. The most recent WordPress update ensured all our tables were <strong>utf8mb4</strong>, so surely we can hard-code this, and reduce the page-load speed?</p>
<p>Yes, we can. WordPress even provides a filter for it.</p>
<pre><code> /**
* Filters the table charset value before the DB is checked.
*
* Passing a non-null value to the filter will effectively short-circuit
* checking the DB for the charset, returning that value instead.
*....
*/
$charset = apply_filters( 'pre_get_table_charset', null, $table );
</code></pre>
<p>Writing the code for this is trivial:</p>
<pre><code>add_filter('pre_get_table_charset', function($charset, $table) {return 'utf8mb4'; }, 10, 2);
</code></pre>
<p>However, this filter is called VERY early in the Wordpress execution stack. It is called before plugins are loaded and before mu-plugins are loaded.</p>
<p>It is called AFTER <code>config/application.php</code>, but at that point, the <code>add_filter()</code> function is not yet defined.</p>
<p>I know there are a billion and one places where I can hack the WordPress core and insert that line, but I'd prefer not to if I can.</p>
<p>Also, we're using a Wordpress Bedrock setup, if that helps at all.</p>
| [
{
"answer_id": 247104,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 0,
"selected": false,
"text": "<p>You can fix it through Session. try</p>\n\n<pre><code>function vv_process_profile_forms() {\n session_start();... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99009/"
] | Question:
---------
Where is the *proper* WordPress place to add a filter for `pre_get_table_charset`, prior to it getting executed?
The `pre_get_table_charset` filter is triggered in `wp-db.php::get_table_charset()`.
---
**Update: Solution**
Mark Kaplun pointed me in the right direction, which is to put the filter into a drop-in. Because we're using an MU setup (as evidenced by my table-name), the easiest and simplest drop-in was `sunrise.php`, which as I understand it, is designed to be loaded super-early anyway.
**Update: Caveat**
Once you successfully have the filter loaded, you will start getting these errors:
```
PHP Notice: Undefined index: wp_2_options in /srv/www/wordpress/web/wp/wp-includes/wp-db.php on line 25xx
```
This is because wp-db.php doesn't cache the result the same way it would if it had to look it up from the DB, and this cache is used by both `wp-db.php::get_table_charset()` and and `wp-db.php::get_col_charset()`.
**Solution:** define a second filter, `pre_get_col_charset`, with 3 parameters, which returns the same value as your `pre_get_table_charset` filter.
```
add_filter('pre_get_col_charset', function($charset, $table, $column) {
return 'utf8mb4';
}, 10, 2);
```
---
**Background:**
---------------
WordPress generates a consistently slow query on our server:
```
SHOW FULL COLUMNS FROM `wp_2_options`
```
This is generated in `wp-db.php::get_table_charset()`, and is used to determine the charset for a table. It is, of course, entirely unnecessary, because we *know* what the charset is. The most recent WordPress update ensured all our tables were **utf8mb4**, so surely we can hard-code this, and reduce the page-load speed?
Yes, we can. WordPress even provides a filter for it.
```
/**
* Filters the table charset value before the DB is checked.
*
* Passing a non-null value to the filter will effectively short-circuit
* checking the DB for the charset, returning that value instead.
*....
*/
$charset = apply_filters( 'pre_get_table_charset', null, $table );
```
Writing the code for this is trivial:
```
add_filter('pre_get_table_charset', function($charset, $table) {return 'utf8mb4'; }, 10, 2);
```
However, this filter is called VERY early in the Wordpress execution stack. It is called before plugins are loaded and before mu-plugins are loaded.
It is called AFTER `config/application.php`, but at that point, the `add_filter()` function is not yet defined.
I know there are a billion and one places where I can hack the WordPress core and insert that line, but I'd prefer not to if I can.
Also, we're using a Wordpress Bedrock setup, if that helps at all. | I meant to answer this earlier. Turns out the problem was developer error (me!). I was using a javascript form handler that would process data and pass it on to the php form handler. Turns out that I was actually loading the .js file twice on the page. Kicked myself real hard for wasting the better part of a day figuring that out.
I had actually fixed it by unbinding the form submit event in the javascript, but then I found the root cause and no longer needed to do that. |
247,126 | <p>Parse error: syntax error, unexpected 'add_action' (T_STRING), expecting function (T_FUNCTION) in C:\xampp\htdocs\web\wp-content\themes\Total\functions.php on line 283</p>
| [
{
"answer_id": 247127,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 1,
"selected": false,
"text": "<p>Open this file </p>\n\n<p><code>C:\\xampp\\htdocs\\web\\wp-content\\themes\\Total\\functions.php</code> </p>\n\n<... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107565/"
] | Parse error: syntax error, unexpected 'add\_action' (T\_STRING), expecting function (T\_FUNCTION) in C:\xampp\htdocs\web\wp-content\themes\Total\functions.php on line 283 | Open this file
`C:\xampp\htdocs\web\wp-content\themes\Total\functions.php`
go to on line `283` and check how you have added add\_action function.
It must be like this.
```
add_action('tag','function_callback' );
```
`add_action` is a function which allows you to attach a function to an action hook and it must not be string eg. `'add_action'`
Please read document about add\_action <http://codex.wordpress.org/Function_Reference/add_action> |
247,152 | <p>I am attempting to edit a specific page via the WordPress admin area while logged in as an Editor, however, the page dies with the following error:</p>
<blockquote>
<p>Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in <strong>[PATH]</strong>/htdocs/wp-includes/meta.php on line 841</p>
</blockquote>
<p>This is only affecting this page, and granted, it is a very content heavy page, but attempting to edit the page as an Administrator works fine. Why might this be?</p>
| [
{
"answer_id": 247162,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 3,
"selected": true,
"text": "<p>Because of this line in <code>wp-admin/admin.php</code>:</p>\n\n<pre><code>if ( current_user_can( 'manage_o... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107581/"
] | I am attempting to edit a specific page via the WordPress admin area while logged in as an Editor, however, the page dies with the following error:
>
> Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in **[PATH]**/htdocs/wp-includes/meta.php on line 841
>
>
>
This is only affecting this page, and granted, it is a very content heavy page, but attempting to edit the page as an Administrator works fine. Why might this be? | Because of this line in `wp-admin/admin.php`:
```
if ( current_user_can( 'manage_options' ) ) {
wp_raise_memory_limit( 'admin' );
}
```
In other words, WordPress raises the memory limit to `WP_MAX_MEMORY_LIMIT` within the admin, but only for users with the `manage_options` capability i.e. administrators.
Your best bet is to [raise the default memory limit](https://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP) in your `wp-config.php`:
```
define( 'WP_MEMORY_LIMIT', '256M' );
``` |
247,196 | <p>I want the conditional to be applied and that it is only displayed on pages, but it does not work, what is wrong?</p>
<pre><code> function luc_add_cutom_fields_to_content( $content ) {
$custom_fields = get_post_custom();
$content .= "<div class='cta-div'>";
if( isset( $custom_fields['luc_name'] ) ) {
$content .= '<h3> '. $custom_fields['luc_name'][0] . '</h3>';
}
if( isset( $custom_fields['luc_description'] ) ) {
$content .= '<p> ' . $custom_fields['luc_description'][0] . '</p>';
}
if( isset( $custom_fields['luc_action'] ) ) {
$content .= '<a href=" ' . $custom_fields['luc_link'][0] . ' ">' . $custom_fields['luc_action'][0] . '</a>';
}
$content .= '</div>';
return $content;
}
if( is_page() ) {
add_filter( 'the_content', 'luc_add_cutom_fields_to_content' );
}
</code></pre>
| [
{
"answer_id": 247202,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe the filter is firing well, but There is no global scope for the current post and the if(isset(...)) can'... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247196",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107241/"
] | I want the conditional to be applied and that it is only displayed on pages, but it does not work, what is wrong?
```
function luc_add_cutom_fields_to_content( $content ) {
$custom_fields = get_post_custom();
$content .= "<div class='cta-div'>";
if( isset( $custom_fields['luc_name'] ) ) {
$content .= '<h3> '. $custom_fields['luc_name'][0] . '</h3>';
}
if( isset( $custom_fields['luc_description'] ) ) {
$content .= '<p> ' . $custom_fields['luc_description'][0] . '</p>';
}
if( isset( $custom_fields['luc_action'] ) ) {
$content .= '<a href=" ' . $custom_fields['luc_link'][0] . ' ">' . $custom_fields['luc_action'][0] . '</a>';
}
$content .= '</div>';
return $content;
}
if( is_page() ) {
add_filter( 'the_content', 'luc_add_cutom_fields_to_content' );
}
``` | [`is_page()`](https://developer.wordpress.org/reference/functions/is_page/) requires `WP_Query` to be initialized and I assume your code runs before this. You can use this function within the filter callback instead:
```
add_filter('the_content', function($c){
return is_page() ? luc_add_cutom_fields_to_content($c) : $c;
});
``` |
247,197 | <p>How to I get the current post id while in admin? I want to use a custom upload dir based on the post ID but i cant seem to retreive it?</p>
<pre><code>add_filter( 'wp_handle_upload_prefilter', 'do_pre_upload' );
function do_pre_upload( $file ) {
add_filter( 'upload_dir', 'do_custom_upload_dir' );
return $file;
}
function do_custom_upload_dir( $param ) {
global $post;
$id = 344; // HOW DO IT GET THE CURRENT POST ID
//$id = $post->ID; // DOESNT WORK DOESNT GET A VALUE?????
$parent = get_post( $id )->post_parent;
if( "client_gallery" == get_post_type( $id ) || "client_gallery" == get_post_type( $parent ) ) {
$mydir = '/client_galleryy/'.$post->ID.'';
$param['path'] = $param['basedir'] . $mydir;
$param['url'] = $param['baseurl'] . $mydir;
}
return $param;
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Here is my full code for my plugin which creates my custom post type, creates a meta box using the meta box plugin and now the code for setting the upload dir for my custom post type / post id. I must have the code for the upload dir in the wrong spot as its not determining that im in my custom post type and that it should be creating the new upload dir for the post?</p>
<pre><code>**
* Plugin Name: My Plugin Name
* Plugin URI: domain.com
* Description: my description
* Version: 1.0.0
* Author: My Name
* Author URI: domain.com
* License: GPL2
*/
// START CREATE CUSTOM POST TYPE
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'client_gallery',
array(
'labels' => array(
'name' => __( 'Galleries' ),
'singular_name' => __( 'Gallery' )
),
'public' => true,
'has_archive' => true,
'supports' => array( 'title' ),
)
);
}
// END CREATE CUSTOM POST TYPE
// START CREATE META BOX
add_filter( 'rwmb_meta_boxes', 'xyz_gallery_meta_boxes' );
function xyz_gallery_meta_boxes( $meta_boxes ) {
$meta_boxes[] = array(
'title' => __( 'Gallery Images', 'textdomain' ),
'post_types' => 'client_gallery',
'fields' => array(
array(
'name' => esc_html__( 'Image', 'textdomain' ),
'id' => "clientImage",
'type' => 'image_advanced',
),
),
);
return $meta_boxes;
}
// END CREATE META BOX
/**
* Modify Upload Directory Based on Post Type
*
* @param Array $dir
*
* @return Array $dir
*/
function wpse_247197( $dir ) {
$request_arr = array( 'upload-attachment', 'editpost', 'editedtag' );
$request = array_change_key_case( $_REQUEST, CASE_LOWER ); // WordPress uses post_id and post_ID
$type = null;
// Are we where we want to be?
if( ! ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $request_arr ) ) ) {
return $dir;
}
if( isset( $request['post_id'] ) ) { // Get Post ID
$id = $request['post_id'];
if( isset( $request['post_type'] ) ) { // Get the post type if it was passed
$type = $request['post_type'];
} else { // If not passed, get post type by ID
$type = get_post_type( $id );
}
} else { // If we can't get a post ID return default directory
return $dir;
}
if( isset( $type, $id ) && in_array( $type, $post_type_arr ) ) {
// Here we can test our type and change the directory name etc. if we really wanted to
if( 'client_gallery' != $type ) {
return $dir;
}
$uploads = apply_filters( "{$type}_upload_directory", "{$type}/{$id}" ); // Set our uploads URL for this type
$dir['url'] = path_join( $dir['baseurl'], $uploads ); // Apply the URL to the directory array
$dir['path'] = path_join( $dir['basedir'], $uploads ); // Apply the Path to the directory array
}
return $dir;
}
add_filter( 'upload_dir', 'wpse_247197' );
// END Modify Upload Directory Based on Post Type
</code></pre>
| [
{
"answer_id": 247201,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p><code>$post</code> is an object, you can get the post id like this</p>\n\n<pre><code> $id = $post->ID;\n</... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247197",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101113/"
] | How to I get the current post id while in admin? I want to use a custom upload dir based on the post ID but i cant seem to retreive it?
```
add_filter( 'wp_handle_upload_prefilter', 'do_pre_upload' );
function do_pre_upload( $file ) {
add_filter( 'upload_dir', 'do_custom_upload_dir' );
return $file;
}
function do_custom_upload_dir( $param ) {
global $post;
$id = 344; // HOW DO IT GET THE CURRENT POST ID
//$id = $post->ID; // DOESNT WORK DOESNT GET A VALUE?????
$parent = get_post( $id )->post_parent;
if( "client_gallery" == get_post_type( $id ) || "client_gallery" == get_post_type( $parent ) ) {
$mydir = '/client_galleryy/'.$post->ID.'';
$param['path'] = $param['basedir'] . $mydir;
$param['url'] = $param['baseurl'] . $mydir;
}
return $param;
}
```
**UPDATE**
Here is my full code for my plugin which creates my custom post type, creates a meta box using the meta box plugin and now the code for setting the upload dir for my custom post type / post id. I must have the code for the upload dir in the wrong spot as its not determining that im in my custom post type and that it should be creating the new upload dir for the post?
```
**
* Plugin Name: My Plugin Name
* Plugin URI: domain.com
* Description: my description
* Version: 1.0.0
* Author: My Name
* Author URI: domain.com
* License: GPL2
*/
// START CREATE CUSTOM POST TYPE
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'client_gallery',
array(
'labels' => array(
'name' => __( 'Galleries' ),
'singular_name' => __( 'Gallery' )
),
'public' => true,
'has_archive' => true,
'supports' => array( 'title' ),
)
);
}
// END CREATE CUSTOM POST TYPE
// START CREATE META BOX
add_filter( 'rwmb_meta_boxes', 'xyz_gallery_meta_boxes' );
function xyz_gallery_meta_boxes( $meta_boxes ) {
$meta_boxes[] = array(
'title' => __( 'Gallery Images', 'textdomain' ),
'post_types' => 'client_gallery',
'fields' => array(
array(
'name' => esc_html__( 'Image', 'textdomain' ),
'id' => "clientImage",
'type' => 'image_advanced',
),
),
);
return $meta_boxes;
}
// END CREATE META BOX
/**
* Modify Upload Directory Based on Post Type
*
* @param Array $dir
*
* @return Array $dir
*/
function wpse_247197( $dir ) {
$request_arr = array( 'upload-attachment', 'editpost', 'editedtag' );
$request = array_change_key_case( $_REQUEST, CASE_LOWER ); // WordPress uses post_id and post_ID
$type = null;
// Are we where we want to be?
if( ! ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $request_arr ) ) ) {
return $dir;
}
if( isset( $request['post_id'] ) ) { // Get Post ID
$id = $request['post_id'];
if( isset( $request['post_type'] ) ) { // Get the post type if it was passed
$type = $request['post_type'];
} else { // If not passed, get post type by ID
$type = get_post_type( $id );
}
} else { // If we can't get a post ID return default directory
return $dir;
}
if( isset( $type, $id ) && in_array( $type, $post_type_arr ) ) {
// Here we can test our type and change the directory name etc. if we really wanted to
if( 'client_gallery' != $type ) {
return $dir;
}
$uploads = apply_filters( "{$type}_upload_directory", "{$type}/{$id}" ); // Set our uploads URL for this type
$dir['url'] = path_join( $dir['baseurl'], $uploads ); // Apply the URL to the directory array
$dir['path'] = path_join( $dir['basedir'], $uploads ); // Apply the Path to the directory array
}
return $dir;
}
add_filter( 'upload_dir', 'wpse_247197' );
// END Modify Upload Directory Based on Post Type
``` | Based on your comments, it sounds like you just want a custom directory for your post type called `client_gallery` which is fairly straight-forward actually. The below just uses the `upload_dir` hook to achieve this:
```
/**
* Modify Upload Directory Based on Post Type
*
* @param Array $dir
*
* @return Array $dir
*/
function wpse_247197( $dir ) {
$request_arr = array( 'upload-attachment', 'editpost', 'editedtag' );
$request = array_change_key_case( $_REQUEST, CASE_LOWER ); // WordPress uses post_id and post_ID
$type = null;
// Are we where we want to be?
if( ! ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $request_arr ) ) ) {
return $dir;
}
if( isset( $request['post_id'] ) ) { // Get Post ID
$id = $request['post_id'];
if( isset( $request['post_type'] ) ) { // Get the post type if it was passed
$type = $request['post_type'];
} else { // If not passed, get post type by ID
$type = get_post_type( $id );
}
} else { // If we can't get a post ID return default directory
return $dir;
}
if( isset( $type, $id ) && ! empty( $type ) && ! empty( $id ) ) {
// Here we can test our type and change the directory name etc. if we really wanted to
if( 'product' != $type ) {
return $dir;
}
$uploads = apply_filters( "{$type}_upload_directory", "{$type}/{$id}" ); // Set our uploads URL for this type
$dir['url'] = path_join( $dir['baseurl'], $uploads ); // Apply the URL to the directory array
$dir['path'] = path_join( $dir['basedir'], $uploads ); // Apply the Path to the directory array
error_log( print_r( $dir, 1 ) );
}
return $dir;
}
add_filter( 'upload_dir', 'wpse_247197' );
```
I've heavily commented the above code so should you have any questions regarding it you may ask in the comments. The idea is that whenever a user uploads to the post type itself it will get uploaded directly to the folder. This is not the case with assigning a pre-uploaded attachment media - moving the files once they've already been uploaded and the URLs have been set would be extremely troublesome. |
247,200 | <p>As a thank you to the hundreds of people who have contributed to my blog through comments, I have created a page which (1) lists them, with (2) how many comments they have made. So far, so good! What would be a great final touch however would be to show (3) how many days since they last posted, and that's where it's gone past my abilities. Any good ideas?</p>
<p>Here's what I've got for the working part:</p>
<pre><code>function top_comment_authors($amount = 250) {
global $wpdb;
$results = $wpdb->get_results('
SELECT
COUNT(comment_author) AS comments_count, comment_author
FROM '.$wpdb->comments.'
WHERE comment_author != "" AND comment_type = "" AND comment_approved = 1
GROUP BY comment_author
ORDER BY comments_count DESC, comment_author ASC
LIMIT '.$amount
);
$output = '<div>';
foreach($results as $result) {
$output .= '<p>'.$result->comment_author.' ('.$result->comments_count.' comments)</p>';
}
$output .= '</div>';
echo $output;
}
</code></pre>
| [
{
"answer_id": 247201,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p><code>$post</code> is an object, you can get the post id like this</p>\n\n<pre><code> $id = $post->ID;\n</... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247200",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107611/"
] | As a thank you to the hundreds of people who have contributed to my blog through comments, I have created a page which (1) lists them, with (2) how many comments they have made. So far, so good! What would be a great final touch however would be to show (3) how many days since they last posted, and that's where it's gone past my abilities. Any good ideas?
Here's what I've got for the working part:
```
function top_comment_authors($amount = 250) {
global $wpdb;
$results = $wpdb->get_results('
SELECT
COUNT(comment_author) AS comments_count, comment_author
FROM '.$wpdb->comments.'
WHERE comment_author != "" AND comment_type = "" AND comment_approved = 1
GROUP BY comment_author
ORDER BY comments_count DESC, comment_author ASC
LIMIT '.$amount
);
$output = '<div>';
foreach($results as $result) {
$output .= '<p>'.$result->comment_author.' ('.$result->comments_count.' comments)</p>';
}
$output .= '</div>';
echo $output;
}
``` | Based on your comments, it sounds like you just want a custom directory for your post type called `client_gallery` which is fairly straight-forward actually. The below just uses the `upload_dir` hook to achieve this:
```
/**
* Modify Upload Directory Based on Post Type
*
* @param Array $dir
*
* @return Array $dir
*/
function wpse_247197( $dir ) {
$request_arr = array( 'upload-attachment', 'editpost', 'editedtag' );
$request = array_change_key_case( $_REQUEST, CASE_LOWER ); // WordPress uses post_id and post_ID
$type = null;
// Are we where we want to be?
if( ! ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $request_arr ) ) ) {
return $dir;
}
if( isset( $request['post_id'] ) ) { // Get Post ID
$id = $request['post_id'];
if( isset( $request['post_type'] ) ) { // Get the post type if it was passed
$type = $request['post_type'];
} else { // If not passed, get post type by ID
$type = get_post_type( $id );
}
} else { // If we can't get a post ID return default directory
return $dir;
}
if( isset( $type, $id ) && ! empty( $type ) && ! empty( $id ) ) {
// Here we can test our type and change the directory name etc. if we really wanted to
if( 'product' != $type ) {
return $dir;
}
$uploads = apply_filters( "{$type}_upload_directory", "{$type}/{$id}" ); // Set our uploads URL for this type
$dir['url'] = path_join( $dir['baseurl'], $uploads ); // Apply the URL to the directory array
$dir['path'] = path_join( $dir['basedir'], $uploads ); // Apply the Path to the directory array
error_log( print_r( $dir, 1 ) );
}
return $dir;
}
add_filter( 'upload_dir', 'wpse_247197' );
```
I've heavily commented the above code so should you have any questions regarding it you may ask in the comments. The idea is that whenever a user uploads to the post type itself it will get uploaded directly to the folder. This is not the case with assigning a pre-uploaded attachment media - moving the files once they've already been uploaded and the URLs have been set would be extremely troublesome. |
247,206 | <p>I've created a page template and used this code to call a post which contains a shortcode: </p>
<pre><code>$post_id = 129;
if( get_post_status( $post_id ) == 'publish' ) {
the_content();
}
</code></pre>
<p>The problem is that this code works fine in the index.php but not in my page template. Why is that?</p>
<p>Help please.</p>
| [
{
"answer_id": 247207,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>get_post()</code> function to get the post content by post id. </p>\n\n<pre><code>$post_id = 12... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247206",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107615/"
] | I've created a page template and used this code to call a post which contains a shortcode:
```
$post_id = 129;
if( get_post_status( $post_id ) == 'publish' ) {
the_content();
}
```
The problem is that this code works fine in the index.php but not in my page template. Why is that?
Help please. | The reason your post is not displaying properly is because functions such as [`the_title()`](https://codex.wordpress.org/Function_Reference/the_title), [`the_permalink()`](https://codex.wordpress.org/Function_Reference/the_permalink), and [`the_content()`](https://developer.wordpress.org/reference/functions/the_content/) ( called [Template Tags](https://codex.wordpress.org/Template_Tags) ) can only be used whenever inside ["The Loop"](https://codex.wordpress.org/The_Loop) or whenever set up properly. There are two options to display your content properly:
**Functions: [`get_post()`](https://developer.wordpress.org/reference/functions/get_post/), [`setup_postdata()`](https://developer.wordpress.org/reference/functions/setup_postdata/) and [`wp_reset_postdata()`](https://codex.wordpress.org/Function_Reference/wp_reset_postdata)**
First you would need to get the WP\_Post Object and pass it into the `setup_postdata()` function so that WordPress can setup the template tags to pull in the correct content. Finally, we would need to reset the `global $post` object by calling `wp_reset_postdata()`.
```
global $post; // Get the current WP_Post object.
$post = get_post( 129 ); // Get our Post Object.
setup_postdata( $post ); // Setup our template tags.
if( 'publish' == $post->post_status ) {
the_content();
}
wp_rest_postdata(); // Reset the global WP_Post object.
```
**Tad Easier using `apply_filters()`**
This is a little more straight-forward and doesn't require so much code which is nice. You won't have access to Template Tags like you would in the above example but if you're just displaying the post content and processing their shortcodes you won't need Template Tags.
```
$post_id = 129;
if( 'publish' == get_post_status( $post_id ) ) {
$post_content = get_post_field( 'post_content', $post_id );
echo apply_filters( 'the_content', $post_content );
}
```
The above grabs the content from the database then runs it through a WordPress filter which processes `the_content()` hook to give us our desired output, shortcodes processed and all. |
247,215 | <p>I have enabled SVG-file-linking on my WP site using the <a href="https://wordpress.org/plugins/safe-svg/" rel="nofollow noreferrer">Safe SVG plug-in</a>, and I'm mostly happy with it. However, I'm having an issue with styling the SVG-paths contained in the external-file I am calling/linikng. Currently, I am unable to create the interactivitiy I desire because I cannot: </p>
<ol>
<li>use my custom javascript/jQuery to add classes to the individual SVG
paths (it works with all my inline svgs, just not the externally linked ones);</li>
<li>change the fills/opacity of the SVG paths in my style.css file, using the
the jQuery applied classes.</li>
</ol>
<p>When I use inline SVG, I can control everything the way I want, my jQuery and CSS work. But when I use the external file using the Safe SVG plug-in, my CSS doesn't seem to interact with the path-elements nor to modify them.</p>
<p>I have found information that speaks to this problem, in-general and beyond WordPress, about CSS and external SVGs (for example <a href="https://stackoverflow.com/questions/22252409/manipulating-external-svg-file-style-properties-with-css">this</a>), but I was wondering if anyone here might have an efficient, simple WordPress-based solution that would allow 1) my jQuery scripts to access and modify the path classes and 2) my CSS to modify the path-elements.</p>
<p>I realize I just go the inline route and save myself the hassle, but I have reasons for wanting to see if I can't accomplish this with independent SVG-files.</p>
<p>Thanks!</p>
| [
{
"answer_id": 247207,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>get_post()</code> function to get the post content by post id. </p>\n\n<pre><code>$post_id = 12... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247215",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
] | I have enabled SVG-file-linking on my WP site using the [Safe SVG plug-in](https://wordpress.org/plugins/safe-svg/), and I'm mostly happy with it. However, I'm having an issue with styling the SVG-paths contained in the external-file I am calling/linikng. Currently, I am unable to create the interactivitiy I desire because I cannot:
1. use my custom javascript/jQuery to add classes to the individual SVG
paths (it works with all my inline svgs, just not the externally linked ones);
2. change the fills/opacity of the SVG paths in my style.css file, using the
the jQuery applied classes.
When I use inline SVG, I can control everything the way I want, my jQuery and CSS work. But when I use the external file using the Safe SVG plug-in, my CSS doesn't seem to interact with the path-elements nor to modify them.
I have found information that speaks to this problem, in-general and beyond WordPress, about CSS and external SVGs (for example [this](https://stackoverflow.com/questions/22252409/manipulating-external-svg-file-style-properties-with-css)), but I was wondering if anyone here might have an efficient, simple WordPress-based solution that would allow 1) my jQuery scripts to access and modify the path classes and 2) my CSS to modify the path-elements.
I realize I just go the inline route and save myself the hassle, but I have reasons for wanting to see if I can't accomplish this with independent SVG-files.
Thanks! | The reason your post is not displaying properly is because functions such as [`the_title()`](https://codex.wordpress.org/Function_Reference/the_title), [`the_permalink()`](https://codex.wordpress.org/Function_Reference/the_permalink), and [`the_content()`](https://developer.wordpress.org/reference/functions/the_content/) ( called [Template Tags](https://codex.wordpress.org/Template_Tags) ) can only be used whenever inside ["The Loop"](https://codex.wordpress.org/The_Loop) or whenever set up properly. There are two options to display your content properly:
**Functions: [`get_post()`](https://developer.wordpress.org/reference/functions/get_post/), [`setup_postdata()`](https://developer.wordpress.org/reference/functions/setup_postdata/) and [`wp_reset_postdata()`](https://codex.wordpress.org/Function_Reference/wp_reset_postdata)**
First you would need to get the WP\_Post Object and pass it into the `setup_postdata()` function so that WordPress can setup the template tags to pull in the correct content. Finally, we would need to reset the `global $post` object by calling `wp_reset_postdata()`.
```
global $post; // Get the current WP_Post object.
$post = get_post( 129 ); // Get our Post Object.
setup_postdata( $post ); // Setup our template tags.
if( 'publish' == $post->post_status ) {
the_content();
}
wp_rest_postdata(); // Reset the global WP_Post object.
```
**Tad Easier using `apply_filters()`**
This is a little more straight-forward and doesn't require so much code which is nice. You won't have access to Template Tags like you would in the above example but if you're just displaying the post content and processing their shortcodes you won't need Template Tags.
```
$post_id = 129;
if( 'publish' == get_post_status( $post_id ) ) {
$post_content = get_post_field( 'post_content', $post_id );
echo apply_filters( 'the_content', $post_content );
}
```
The above grabs the content from the database then runs it through a WordPress filter which processes `the_content()` hook to give us our desired output, shortcodes processed and all. |
247,219 | <p>I'm using the following code (<a href="http://www.ordinarycoder.com/paginate_links-class-ul-li-bootstrap/" rel="nofollow noreferrer">from here</a>) to paginate links:</p>
<pre><code>function custom_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
$pages = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'prev_next' => false,
'type' => 'array',
'prev_next' => TRUE,
'prev_text' => __('«'),
'next_text' => __('»'),
) );
if( is_array( $pages ) ) {
$paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
echo '<ul class="pagination">';
foreach ( $pages as $page ) {
echo "<li>$page</li>";
}
echo '</ul>';
}
}
</code></pre>
<p>The output of this is using <code>echo custom_pagination();</code>:</p>
<pre><code><ul class="pagination">
<li class="page-item">
<a class="page-numbers" href="example.com/page/1">1</a>
</li>
</ul>
</code></pre>
<p>How can I change the output to this?:</p>
<pre><code><ul class="pagination">
<li class="page-item">
<a class="page-link" href="example.com/page/1">1</a>
</li>
</ul>
</code></pre>
<p>I'm trying to make a bootstrap theme, but I can't seem to replace the <code>page-numbers</code> class with the bootstrap <code>page-link</code> class.</p>
| [
{
"answer_id": 247225,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 0,
"selected": false,
"text": "<p>Tracking through this, it appears that there isn't a way to pass a class through the <code>paginate_links</co... | 2016/11/23 | [
"https://wordpress.stackexchange.com/questions/247219",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107619/"
] | I'm using the following code ([from here](http://www.ordinarycoder.com/paginate_links-class-ul-li-bootstrap/)) to paginate links:
```
function custom_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
$pages = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'prev_next' => false,
'type' => 'array',
'prev_next' => TRUE,
'prev_text' => __('«'),
'next_text' => __('»'),
) );
if( is_array( $pages ) ) {
$paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
echo '<ul class="pagination">';
foreach ( $pages as $page ) {
echo "<li>$page</li>";
}
echo '</ul>';
}
}
```
The output of this is using `echo custom_pagination();`:
```
<ul class="pagination">
<li class="page-item">
<a class="page-numbers" href="example.com/page/1">1</a>
</li>
</ul>
```
How can I change the output to this?:
```
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="example.com/page/1">1</a>
</li>
</ul>
```
I'm trying to make a bootstrap theme, but I can't seem to replace the `page-numbers` class with the bootstrap `page-link` class. | The `paginate_links()` function, located in [`wp-includes/general-template.php`](https://github.com/WordPress/WordPress/blob/master/wp-includes/general-template.php#L3233), doesn't allow for certain parts of the HTML (such as the `page-numbers` class) to be customized.
A simple string replacement will not work due to the way that the classes are generated, as highlighted in this excerpt of code from `paginate_links()`:
```
$page_links[] = '<a class="prev page-numbers" href="' . esc_url( apply_filters( 'paginate_links', $link ) ) . '">' . $args['prev_text'] . '</a>';
endif;
for ( $n = 1; $n <= $total; $n++ ) :
if ( $n == $current ) :
$page_links[] = "<span class='page-numbers current'>" . $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number'] . "</span>";
```
Here is an updated version of your `custom_pagination()` function, which uses DOMXpath to to find instances elements with the `page-numbers` class, then a string replacement is done to change the class to `page-link`. For better compatibility with Bootstrap, the `current` class is also replaced with `active`. Finally, `class="mynewclass"` is added to the `<li>` which contains the current item.
```
function wpse247219_custom_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
$pages = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'prev_next' => false,
'type' => 'array',
'prev_next' => true,
'prev_text' => __( '«', 'text-domain' ),
'next_text' => __( '»', 'text-domain'),
) );
$output = '';
if ( is_array( $pages ) ) {
$paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var( 'paged' );
$output .= '<ul class="pagination">';
foreach ( $pages as $page ) {
$output .= "<li>$page</li>";
}
$output .= '</ul>';
// Create an instance of DOMDocument
$dom = new \DOMDocument();
// Populate $dom with $output, making sure to handle UTF-8, otherwise
// problems will occur with UTF-8 characters.
$dom->loadHTML( mb_convert_encoding( $output, 'HTML-ENTITIES', 'UTF-8' ) );
// Create an instance of DOMXpath and all elements with the class 'page-numbers'
$xpath = new \DOMXpath( $dom );
// http://stackoverflow.com/a/26126336/3059883
$page_numbers = $xpath->query( "//*[contains(concat(' ', normalize-space(@class), ' '), ' page-numbers ')]" );
// Iterate over the $page_numbers node...
foreach ( $page_numbers as $page_numbers_item ) {
// Add class="mynewclass" to the <li> when its child contains the current item.
$page_numbers_item_classes = explode( ' ', $page_numbers_item->attributes->item(0)->value );
if ( in_array( 'current', $page_numbers_item_classes ) ) {
$list_item_attr_class = $dom->createAttribute( 'class' );
$list_item_attr_class->value = 'mynewclass';
$page_numbers_item->parentNode->appendChild( $list_item_attr_class );
}
// Replace the class 'current' with 'active'
$page_numbers_item->attributes->item(0)->value = str_replace(
'current',
'active',
$page_numbers_item->attributes->item(0)->value );
// Replace the class 'page-numbers' with 'page-link'
$page_numbers_item->attributes->item(0)->value = str_replace(
'page-numbers',
'page-link',
$page_numbers_item->attributes->item(0)->value );
}
// Save the updated HTML and output it.
$output = $dom->saveHTML();
}
return $output;
}
```
**Usage:**
```
echo wpse247219_custom_pagination();
```
**Generated HTML:**
```
<ul class="pagination">
<li class="mynewclass"><span class="page-link active">1</span></li>
<li><a class="page-link" href="http://localhost/page/2/">2</a></li>
<li><a class="page-link" href="http://localhost/page/3/">3</a></li>
<li><span class="page-link dots">…</span></li>
<li><a class="page-link" href="http://localhost/page/5/">5</a></li>
<li><a class="next page-link" href="http://localhost/page/2/">»</a></li>
</ul>
``` |
247,251 | <p>This is really a two stage question, for not very relevant context you can look at this question - <a href="https://wordpress.stackexchange.com/questions/227245/how-to-customize-a-shortcode-using-the-customizer">How to customize a shortcode using the customizer</a>. In brief I got a widget and a shortcode that implement the same functionality and that is customized in the customizer by adapting the form generated for the widget into a customizer section.</p>
<p>Now I would like to use partial refresh when possible, but some ssettings require CSS and/or JS changes and a full refresh is a must to reflect changes (if you want to avoid writting crazy JS code just for that).</p>
<p>So the easier part of the question is the shortcode section - how to have two
settings in the saame section with one doing a partial refresh while the other doing a full one.</p>
<p>The advanced part is to have it working for the widget as well.</p>
<p>To make it less theoretical, here is the code in question - <a href="https://github.com/tiptoppress/category-posts-widget/tree/4.7.1" rel="nofollow noreferrer">https://github.com/tiptoppress/category-posts-widget/tree/4.7.1</a></p>
<p>That is a "recent posts" type of widget which lets you specify filtering criteria based on <code>wp_query</code> settings, therefor some settings just require the trip to the server to produce a "preview". Some other setting control the display by inserting CSS rules, while some other setting - browser side cropping, need JS for implementation and the JS need to be activated per widget, and for this the ids of the widgets are enqueued.</p>
<p>Partials are good solution for the <code>wp_query</code> related part, but not for the CSS. In theory you can enqueue JS in the partial (I assume), but it is not obvious how to dequeue it.</p>
<p>The question here is not really if it is possible to hack something that will make it work, as given enough effort everything can be massaged into a working state, the problem is to do it in a way which will not violate DRY and KISS principals and show the user exactly what he will see on the front end and not just an approximation. In english - I don't want to fork how the widget's front end works just so I will be able to claim that I use partial as the difference in actual user UX between a refresh and a partial is not that big to justify forking the front end code.</p>
<p>(yes this is kind of two questions in one, but maybe the answers are not as different as I suspect they will be)</p>
| [
{
"answer_id": 247514,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 4,
"selected": true,
"text": "<p><strong>tl;dr</strong> See <a href=\"https://gist.github.com/westonruter/d4a21d8c891974e808975dcdfe97625d\"... | 2016/11/24 | [
"https://wordpress.stackexchange.com/questions/247251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23970/"
] | This is really a two stage question, for not very relevant context you can look at this question - [How to customize a shortcode using the customizer](https://wordpress.stackexchange.com/questions/227245/how-to-customize-a-shortcode-using-the-customizer). In brief I got a widget and a shortcode that implement the same functionality and that is customized in the customizer by adapting the form generated for the widget into a customizer section.
Now I would like to use partial refresh when possible, but some ssettings require CSS and/or JS changes and a full refresh is a must to reflect changes (if you want to avoid writting crazy JS code just for that).
So the easier part of the question is the shortcode section - how to have two
settings in the saame section with one doing a partial refresh while the other doing a full one.
The advanced part is to have it working for the widget as well.
To make it less theoretical, here is the code in question - <https://github.com/tiptoppress/category-posts-widget/tree/4.7.1>
That is a "recent posts" type of widget which lets you specify filtering criteria based on `wp_query` settings, therefor some settings just require the trip to the server to produce a "preview". Some other setting control the display by inserting CSS rules, while some other setting - browser side cropping, need JS for implementation and the JS need to be activated per widget, and for this the ids of the widgets are enqueued.
Partials are good solution for the `wp_query` related part, but not for the CSS. In theory you can enqueue JS in the partial (I assume), but it is not obvious how to dequeue it.
The question here is not really if it is possible to hack something that will make it work, as given enough effort everything can be massaged into a working state, the problem is to do it in a way which will not violate DRY and KISS principals and show the user exactly what he will see on the front end and not just an approximation. In english - I don't want to fork how the widget's front end works just so I will be able to claim that I use partial as the difference in actual user UX between a refresh and a partial is not that big to justify forking the front end code.
(yes this is kind of two questions in one, but maybe the answers are not as different as I suspect they will be) | **tl;dr** See [standalone example plugin](https://gist.github.com/westonruter/d4a21d8c891974e808975dcdfe97625d) that demonstrates initiating a full refresh when a selective refresh request enqueues different scripts or styles and also which re-initializes JS behaviors for selectively-refreshed partial placement containers.
---
I understand the goal to be to minimize the amount of logic required in the customizer to preview changes to updated partials that enqueue different scripts and styles based on a setting change. The solution here has been accounted for in the design of selective refresh in the customizer. In particular, when a partial is rendered it does so in the context of the URL on which it will be displayed. This means that all of the scripts and styles enqueued for that given URL should be enqueued when the partial is rendered. To this end, the `customize_render_partials_before` action has the following docs:
>
> **Fires immediately before partials are rendered.**
>
>
> Plugins may do things like call `wp_enqueue_scripts()` and gather a list of the scripts
> and styles which may get enqueued in the response.
>
>
>
And eventually core may go ahead and do `wp_enqueue_scripts()` itself by default. For the initial implementation of selective refresh, however, the enqueueing was left to plugins.
Once the scripts and styles have been enqueued, the need is then to communicate back to the JS in the page which assets have been enqueued in the response. This is what the `customize_render_partials_response` filter is for, as its docs indicate:
>
> **Filters the response from rendering the partials.**
>
>
> Plugins may use this filter to inject `$scripts` and `$styles`, which are dependencies
> for the partials being rendered. The response data will be available to the client via
> the `render-partials-response` JS event, so the client can then inject the scripts and
> styles into the DOM if they have not already been enqueued there.
>
>
> If plugins do this, they'll need to take care for any scripts that do `document.write()`
> and make sure that these are not injected, or else to override the function to no-op,
> or else the page will be destroyed.
>
>
> Plugins should be aware that `$scripts` and `$styles` may eventually be included by
> default in the response.
>
>
>
The filtered `$response` array is exposed in JavaScript via a `render-partials-response` event triggered on `wp.customize.selectiveRefresh`. So to initiate a full refresh when a selective refresh request enqueues assets not already on the page, what is needed is to first export the handles for enqueued scripts and styles for the initial page load, and then in the `render-partials-response` JS event check to see if the enqueued script and style handles during the selective refresh request are the same that were initially enqueued on the page. If they differ, then the JS just needs to call `wp.customize.selectiveRefresh.requestFullRefresh()`. The following JS would be enqueued only in the customizer preview:
```
/* global wp, _ */
/* exported WPSE_247251 */
var WPSE_247251 = (function( api ) {
var component = {
data: {
enqueued_styles: {},
enqueued_scripts: {}
}
};
/**
* Init.
*
* @param {object} data Data exported from PHP.
* @returns {void}
*/
component.init = function init( data ) {
if ( data ) {
_.extend( component.data, data );
}
api.selectiveRefresh.bind( 'render-partials-response', component.handleRenderPartialsResponse );
};
/**
* Handle render-partials-response event, requesting full refresh if newly-enqueued styles/styles differ.
*
* @param {object} response Response.
* @returns {void}
*/
component.handleRenderPartialsResponse = function handleRenderPartialsResponse( response ) {
if ( ! response.wpse_247251 ) {
return;
}
if ( ! _.isEqual( component.data.enqueued_styles, response.wpse_247251.enqueued_styles ) ) {
api.selectiveRefresh.requestFullRefresh();
}
if ( ! _.isEqual( component.data.enqueued_scripts, response.wpse_247251.enqueued_scripts ) ) {
api.selectiveRefresh.requestFullRefresh();
}
};
return component;
})( wp.customize );
```
An inline script can be added in PHP to export the `enqueued_scripts` and `enqueued_styles` by then calling `WPSE_247251.init( data )`.
When a partial is selectively refreshed, a bit more is needed to ensure that any JS behaviors associated with the container are re-initialized. Specifically, the JS should be engineered so that there is a function that is responsible for finding elements to set up in the DOM. By default this function should look at the entire `body`. But then the JS can check to see if it is running in the context of the customizer preview, and if so, listen for the `partial-content-rendered` event triggered on `wp.customize.selectiveRefresh` to then call that function passing in `placement.container` as the scope for initializing rather than the entire `body`:
```
if ( 'undefined' !== typeof wp && 'undefined' !== typeof wp.customize && 'undefined' !== typeof wp.customize.selectiveRefresh ) {
wp.customize.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {
initializeAllElements( $( placement.container ) );
} );
}
```
So again, see a [standalone example plugin](https://gist.github.com/westonruter/d4a21d8c891974e808975dcdfe97625d) that demonstrates initiating a full refresh when when a selective refresh request enqueues different scripts or styles and also which re-initializes JS behaviors for selectively-refreshed partial placement containers.
In closing, if WordPress themes could just be implemented with something like React we could avoid adding special support for selectively refreshing elements on the page since the changes to the state would automatically cause the desired changes in the DOM. Since we're not there yet (although prototypes are being worked on for this) we have to settle for the next best experience for quickly refreshing parts of a page with the minimal extra effort for developers: selective refresh. |
247,258 | <p>How to check if search query contain some characters? For example I would like to check if search query contain "/".</p>
<p>I tried <a href="https://stackoverflow.com/questions/17940444/if-search-query-is-met-function">this answer</a> but it is not working for me. Just to say I am using custom search base.</p>
<p>Example:</p>
<p>site.com/myseachbase/keyword</p>
<p>where "myseachbase" is my custom search base. What I need is way to check if search query has "/", in some cases it is at the end of search query, for example:</p>
<p>site.com/myseachbase/keyword/</p>
<p>How to check for that ending "/" in search URL?</p>
<hr>
<p><strong>QUESTION UPDATE:</strong></p>
<hr>
<p>Problem is that I have some custom URLs like:</p>
<p>site.com/myseachbase/keyword</p>
<p>They are practically search results, even visitor open them by clicking on link(s), not by using normal site search.</p>
<p>I need to make them indexable only if:</p>
<ul>
<li>there are search results</li>
<li>it is first search results page, not for any other /page/x</li>
<li>search query has specific keyword(s)</li>
<li>search results are correct and usefull results</li>
<li>plus to add some quality content prepared by editor based on search keyword</li>
</ul>
<p>After I have done that part, I have nice quality content, custom text based on search query + some images (images are search results) on URLs like:</p>
<p>site.com/myseachbase/keyword</p>
<p>but, if you add "/" at the you will get same page, but another URL, which will met conditions to be indexable too. So, I need way to put "noindex" tag in case if it is that duplicate URL, URL with "/" at the end, because I have no option to create canonicial URL. For that I need something to check for "/".</p>
| [
{
"answer_id": 247264,
"author": "Emil",
"author_id": 80532,
"author_profile": "https://wordpress.stackexchange.com/users/80532",
"pm_score": 0,
"selected": false,
"text": "<p>You'll need to hook onto the search query through <code>pre_get_posts</code>. The following snippet will search ... | 2016/11/24 | [
"https://wordpress.stackexchange.com/questions/247258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25053/"
] | How to check if search query contain some characters? For example I would like to check if search query contain "/".
I tried [this answer](https://stackoverflow.com/questions/17940444/if-search-query-is-met-function) but it is not working for me. Just to say I am using custom search base.
Example:
site.com/myseachbase/keyword
where "myseachbase" is my custom search base. What I need is way to check if search query has "/", in some cases it is at the end of search query, for example:
site.com/myseachbase/keyword/
How to check for that ending "/" in search URL?
---
**QUESTION UPDATE:**
---
Problem is that I have some custom URLs like:
site.com/myseachbase/keyword
They are practically search results, even visitor open them by clicking on link(s), not by using normal site search.
I need to make them indexable only if:
* there are search results
* it is first search results page, not for any other /page/x
* search query has specific keyword(s)
* search results are correct and usefull results
* plus to add some quality content prepared by editor based on search keyword
After I have done that part, I have nice quality content, custom text based on search query + some images (images are search results) on URLs like:
site.com/myseachbase/keyword
but, if you add "/" at the you will get same page, but another URL, which will met conditions to be indexable too. So, I need way to put "noindex" tag in case if it is that duplicate URL, URL with "/" at the end, because I have no option to create canonicial URL. For that I need something to check for "/". | After the question's update, I think that you need to set the canonical URL:
```
add_action( 'wp_head', 'cyb_search_results_canonical_URL' );
function cyb_search_results_canonical_URL() {
if( is_search() ) {
$link = get_search_link();
echo '<link rel="canonical" href="' . esc_url( $link ) . '">';
}
}
```
And your problem with duplicated content is fixed. |
247,328 | <p>I'm working within a child theme so I don't want to edit the file that is registering a Portfolio CPT to my site. I used a plugin to change the name from Portfolio to Stories, but the plugin doesn't give an option for the slug.</p>
<p>I tried using the following function:</p>
<pre><code>function change_slug_of_post_type_portfolio() {
register_post_type('portfolio', array('rewrite' => array ('slug' => 'stories',)));
}
add_action('init', 'change_slug_of_post_type_portfolio', 20);
</code></pre>
<p>But it removes Portfolio entirely from the WordPress admin sidebar.</p>
| [
{
"answer_id": 247330,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 6,
"selected": true,
"text": "<p>The <a href=\"https://developer.wordpress.org/reference/hooks/register_post_type_args/\" rel=\"noreferrer\">... | 2016/11/24 | [
"https://wordpress.stackexchange.com/questions/247328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96257/"
] | I'm working within a child theme so I don't want to edit the file that is registering a Portfolio CPT to my site. I used a plugin to change the name from Portfolio to Stories, but the plugin doesn't give an option for the slug.
I tried using the following function:
```
function change_slug_of_post_type_portfolio() {
register_post_type('portfolio', array('rewrite' => array ('slug' => 'stories',)));
}
add_action('init', 'change_slug_of_post_type_portfolio', 20);
```
But it removes Portfolio entirely from the WordPress admin sidebar. | The [`register_post_type_args`](https://developer.wordpress.org/reference/hooks/register_post_type_args/) filter can be used to modify post type arguments:
```
add_filter( 'register_post_type_args', 'wpse247328_register_post_type_args', 10, 2 );
function wpse247328_register_post_type_args( $args, $post_type ) {
if ( 'portfolio' === $post_type ) {
$args['rewrite']['slug'] = 'stories';
}
return $args;
}
``` |
247,332 | <p>I need to import images from an url and return the image id</p>
<p>is it possible to make a function like this?</p>
<pre><code> <?php
$link = 'https://mosaic01.ztat.net/vgs/media/pdp-zoom/NI/11/3D/03/4D/11/NI113D034-D11@12.jpg';
$title = 'the image title';
$alt = 'the image alt';
$image_id = insert_image($link, $title, $alt);
?>
</code></pre>
| [
{
"answer_id": 247333,
"author": "Felipe Rodrigues",
"author_id": 104101,
"author_profile": "https://wordpress.stackexchange.com/users/104101",
"pm_score": 0,
"selected": false,
"text": "<p>What id? The HTML ID? If not, maybe you need a regex to search the url in order to find a pattern ... | 2016/11/24 | [
"https://wordpress.stackexchange.com/questions/247332",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107702/"
] | I need to import images from an url and return the image id
is it possible to make a function like this?
```
<?php
$link = 'https://mosaic01.ztat.net/vgs/media/pdp-zoom/NI/11/3D/03/4D/11/NI113D034-D11@12.jpg';
$title = 'the image title';
$alt = 'the image alt';
$image_id = insert_image($link, $title, $alt);
?>
``` | Take a look at side loading images. [`media_sideload_image()`](https://codex.wordpress.org/Function_Reference/media_sideload_image)/[`wp_handle_sideload()`](https://codex.wordpress.org/Function_Reference/wp_handle_sideload) and get the ID from the URL. [`attachment_url_to_postid`](https://developer.wordpress.org/reference/functions/attachment_url_to_postid/).
```
<?php
$url = "http://wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png";
$title = "Some Image Title";
$alt_text = "Some Alt Text";
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// sideload the image --- requires the files above to work correctly
$src = media_sideload_image( $url, null, null, 'src' );
// convert the url to image id
$image_id = attachment_url_to_postid( $src );
if( $image_id ) {
// make sure the post exists
$image = get_post( $image_id );
if( $image) {
// Add title to image
wp_update_post( array (
'ID' => $image->ID,
'post_title' => "Some Image Title",
) );
// Add Alt text to image
update_post_meta($image->ID, '_wp_attachment_image_alt', $alt_text);
}
}
``` |
247,367 | <p>I would like to have a different template for categories and subcategories
The categories template is set in categories.php
is it somehow possible to load the subcategories template from subcategories.php or something like that?</p>
| [
{
"answer_id": 247376,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#filter-hierarchy\" rel=\"nofollow noref... | 2016/11/25 | [
"https://wordpress.stackexchange.com/questions/247367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107713/"
] | I would like to have a different template for categories and subcategories
The categories template is set in categories.php
is it somehow possible to load the subcategories template from subcategories.php or something like that? | [The template hierarchy has filters](https://developer.wordpress.org/themes/basics/template-hierarchy/#filter-hierarchy) for all types of templates. Here we can use `category_template`, check if the current category has a parent, and load the `subcategory.php` file in that case:
```
function wpd_subcategory_template( $template ) {
$cat = get_queried_object();
if ( isset( $cat ) && $cat->category_parent ) {
$template = locate_template( 'subcategory.php' );
}
return $template;
}
add_filter( 'category_template', 'wpd_subcategory_template' );
``` |
247,371 | <p>In my Customizer, I have a checkbox to "Display Title". I want the title to display by default (which it is in the Customizer) but the Customizer settings need to be saved in order for it to display on the live site. I would like it to display without having to save the settings first.</p>
<p>This is the code I have in my template file:</p>
<pre><code><?php if( get_theme_mod( 'display_header_image_title' ) == '1') { ?>
<h1 id="header-image-title"><?php echo get_theme_mod( 'header_image_title' , __( 'default text', 'myTheme' )); ?></h1>
<?php } ?>
</code></pre>
<p>This is the code I have in my customizer.php file:</p>
<pre><code>// Title
$wp_customize->add_setting( 'header_image_title', array(
'default' => __('Title','myTheme'),
'transport' => 'postMessage'
) );
$wp_customize->add_control( 'header_image_title', array(
'label' => __('Title','myTheme'),
'type' => 'text'
) );
// Display Title
$wp_customize->add_setting( 'display_header_image_title', array(
'default' => true,
'transport' => 'postMessage'
) );
$wp_customize->add_control( 'display_header_image_title', array(
'label' => __('Display Title','myTheme'),
'type' => 'checkbox'
) );
</code></pre>
<p>I suspect this line needs to be edited in the template file:</p>
<pre><code><?php if( get_theme_mod( 'display_header_image_title' ) == '1') { ?>
</code></pre>
| [
{
"answer_id": 247373,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p><code>get_theme_mod()</code> has a second parameter where you can set the default value, the value to use if t... | 2016/11/25 | [
"https://wordpress.stackexchange.com/questions/247371",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
] | In my Customizer, I have a checkbox to "Display Title". I want the title to display by default (which it is in the Customizer) but the Customizer settings need to be saved in order for it to display on the live site. I would like it to display without having to save the settings first.
This is the code I have in my template file:
```
<?php if( get_theme_mod( 'display_header_image_title' ) == '1') { ?>
<h1 id="header-image-title"><?php echo get_theme_mod( 'header_image_title' , __( 'default text', 'myTheme' )); ?></h1>
<?php } ?>
```
This is the code I have in my customizer.php file:
```
// Title
$wp_customize->add_setting( 'header_image_title', array(
'default' => __('Title','myTheme'),
'transport' => 'postMessage'
) );
$wp_customize->add_control( 'header_image_title', array(
'label' => __('Title','myTheme'),
'type' => 'text'
) );
// Display Title
$wp_customize->add_setting( 'display_header_image_title', array(
'default' => true,
'transport' => 'postMessage'
) );
$wp_customize->add_control( 'display_header_image_title', array(
'label' => __('Display Title','myTheme'),
'type' => 'checkbox'
) );
```
I suspect this line needs to be edited in the template file:
```
<?php if( get_theme_mod( 'display_header_image_title' ) == '1') { ?>
``` | `get_theme_mod()` has a second parameter where you can set the default value, the value to use if the option is not set.
So, if the default value is `"1"`, you can use:
```
get_theme_mod( 'display_header_image_title', '1' )
```
Then, if there is not value for `display_header_image_title` (no value in database), `"1"` is used. So, you could check the exact value:
```
if( get_theme_mod( 'display_header_image_title', '1' ) === '1' ) {
}
```
Or just true/false:
```
if( get_theme_mod( 'display_header_image_title', '1' ) ) {
}
``` |
247,399 | <p>On our blog, only one page is responsive. All other pages are not reorganized when they we access them. I checked all of the settings and searched the web for a while but I could not find a hint about why this happens.</p>
<p>Here's the page that works: <a href="http://blog.tryd.com.br/archives/4494" rel="nofollow noreferrer">http://blog.tryd.com.br/archives/4494</a></p>
<p>Any other page looks wrong on cell phones.</p>
<p>Any ideas of why is it happening?</p>
| [
{
"answer_id": 247373,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p><code>get_theme_mod()</code> has a second parameter where you can set the default value, the value to use if t... | 2016/11/25 | [
"https://wordpress.stackexchange.com/questions/247399",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107738/"
] | On our blog, only one page is responsive. All other pages are not reorganized when they we access them. I checked all of the settings and searched the web for a while but I could not find a hint about why this happens.
Here's the page that works: <http://blog.tryd.com.br/archives/4494>
Any other page looks wrong on cell phones.
Any ideas of why is it happening? | `get_theme_mod()` has a second parameter where you can set the default value, the value to use if the option is not set.
So, if the default value is `"1"`, you can use:
```
get_theme_mod( 'display_header_image_title', '1' )
```
Then, if there is not value for `display_header_image_title` (no value in database), `"1"` is used. So, you could check the exact value:
```
if( get_theme_mod( 'display_header_image_title', '1' ) === '1' ) {
}
```
Or just true/false:
```
if( get_theme_mod( 'display_header_image_title', '1' ) ) {
}
``` |
247,402 | <p>I am enqueuing some javascript that injects SVGs into my page's DOM (called <a href="https://github.com/iconic/SVGInjector" rel="nofollow noreferrer">SVGInjector</a>); it works great except for one thing: there is an undesirable "blink"/shift of elements on my screen where the injected elements are placed upon loading. Apparently this blink has a name I found months after asking the question, it is called the Flash of Unstyled Content (or FOUC) and even has its own <a href="https://en.wikipedia.org/wiki/Flash_of_unstyled_content" rel="nofollow noreferrer">Wiki</a>.</p>
<p>The reason for this shift seems pretty clear: the page's other elements are apparently drawn <em>before</em> the js that injects the SVGs runs, and then, once they are inserted, the page changes to accommodate the added SVGs. I mentioned it here in an answer to my own question that I asked yesterday: <a href="https://wordpress.stackexchange.com/a/247315/105196">https://wordpress.stackexchange.com/a/247315/105196</a></p>
<h1>How to prevent element movement due to late injection?</h1>
<p>I am hoping someone can tell me how to prevent this blinking/shift. I believe the solution would entail either 1) delaying the drawing of the page's other elements until after the SVG is injected via the enqueued js or 2) making the js run earlier, but I'm not sure. Even if this is what I need to do, I'm not sure how to do it.</p>
<h3>Some clues, perhaps</h3>
<p>There is some info here about running js before loading the whole page, <a href="https://stackoverflow.com/questions/2920129/can-i-run-javascript-before-the-whole-page-is-loaded">https://stackoverflow.com/questions/2920129/can-i-run-javascript-before-the-whole-page-is-loaded</a>, but it is about web-coding, in general, not WordPress specific. I don't understand enough about WP and enqueuing to figure out how to adapt these solutions.</p>
<h1>The Code</h1>
<h3>How I enqueued the js in functions.php:</h3>
<pre><code>function mytheme_enqueue_front_page_scripts() {
if( is_front_page() )
{
wp_enqueue_script( 'injectSVG', get_stylesheet_directory_uri() . '/js/svg-injector.min.js', array( 'jquery' ), null, true );
wp_enqueue_script( 'custom', get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ), null, true );
}
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_front_page_scripts' );
</code></pre>
<p>The problem may lie in the SVGinjector script itself, it might specifically have instructions to wait until the other elements are drawn. You can take a look at it here if you think it might be the cause:</p>
<h3>The SVGInjector js script (enqueued as 'injectSVG')</h3>
<pre><code>!function(t,e){"use strict";function r(t){t=t.split(" ");for(var e={},r=t.length,n=[];r--;)e.hasOwnProperty(t[r])||(e[t[r]]=1,n.unshift(t[r]));return n.join(" ")}var n="file:"===t.location.protocol,i=e.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1"),o=Array.prototype.forEach||function(t,e){if(void 0===this||null===this||"function"!=typeof t)throw new TypeError;var r,n=this.length>>>0;for(r=0;n>r;++r)r in this&&t.call(e,this[r],r,this)},a={},l=0,s=[],u=[],c={},f=function(t){return t.cloneNode(!0)},p=function(t,e){u[t]=u[t]||[],u[t].push(e)},d=function(t){for(var e=0,r=u[t].length;r>e;e++)!function(e){setTimeout(function(){u[t][e](f(a[t]))},0)}(e)},v=function(e,r){if(void 0!==a[e])a[e]instanceof SVGSVGElement?r(f(a[e])):p(e,r);else{if(!t.XMLHttpRequest)return r("Browser does not support XMLHttpRequest"),!1;a[e]={},p(e,r);var i=new XMLHttpRequest;i.onreadystatechange=function(){if(4===i.readyState){if(404===i.status||null===i.responseXML)return r("Unable to load SVG file: "+e),n&&r("Note: SVG injection ajax calls do not work locally without adjusting security setting in your browser. Or consider using a local webserver."),r(),!1;if(!(200===i.status||n&&0===i.status))return r("There was a problem injecting the SVG: "+i.status+" "+i.statusText),!1;if(i.responseXML instanceof Document)a[e]=i.responseXML.documentElement;else if(DOMParser&&DOMParser instanceof Function){var t;try{var o=new DOMParser;t=o.parseFromString(i.responseText,"text/xml")}catch(l){t=void 0}if(!t||t.getElementsByTagName("parsererror").length)return r("Unable to parse SVG file: "+e),!1;a[e]=t.documentElement}d(e)}},i.open("GET",e),i.overrideMimeType&&i.overrideMimeType("text/xml"),i.send()}},h=function(e,n,a,u){var f=e.getAttribute("data-src")||e.getAttribute("src");if(!/\.svg/i.test(f))return void u("Attempted to inject a file with a non-svg extension: "+f);if(!i){var p=e.getAttribute("data-fallback")||e.getAttribute("data-png");return void(p?(e.setAttribute("src",p),u(null)):a?(e.setAttribute("src",a+"/"+f.split("/").pop().replace(".svg",".png")),u(null)):u("This browser does not support SVG and no PNG fallback was defined."))}-1===s.indexOf(e)&&(s.push(e),e.setAttribute("src",""),v(f,function(i){if("undefined"==typeof i||"string"==typeof i)return u(i),!1;var a=e.getAttribute("id");a&&i.setAttribute("id",a);var p=e.getAttribute("title");p&&i.setAttribute("title",p);var d=[].concat(i.getAttribute("class")||[],"injected-svg",e.getAttribute("class")||[]).join(" ");i.setAttribute("class",r(d));var v=e.getAttribute("style");v&&i.setAttribute("style",v);var h=[].filter.call(e.attributes,function(t){return/^data-\w[\w\-]*$/.test(t.name)});o.call(h,function(t){t.name&&t.value&&i.setAttribute(t.name,t.value)});var g,m,b,y,A,w={clipPath:["clip-path"],"color-profile":["color-profile"],cursor:["cursor"],filter:["filter"],linearGradient:["fill","stroke"],marker:["marker","marker-start","marker-mid","marker-end"],mask:["mask"],pattern:["fill","stroke"],radialGradient:["fill","stroke"]};Object.keys(w).forEach(function(t){g=t,b=w[t],m=i.querySelectorAll("defs "+g+"[id]");for(var e=0,r=m.length;r>e;e++){y=m[e].id,A=y+"-"+l;var n;o.call(b,function(t){n=i.querySelectorAll("["+t+'*="'+y+'"]');for(var e=0,r=n.length;r>e;e++)n[e].setAttribute(t,"url(#"+A+")")}),m[e].id=A}}),i.removeAttribute("xmlns:a");for(var x,S,k=i.querySelectorAll("script"),j=[],G=0,T=k.length;T>G;G++)S=k[G].getAttribute("type"),S&&"application/ecmascript"!==S&&"application/javascript"!==S||(x=k[G].innerText||k[G].textContent,j.push(x),i.removeChild(k[G]));if(j.length>0&&("always"===n||"once"===n&&!c[f])){for(var M=0,V=j.length;V>M;M++)new Function(j[M])(t);c[f]=!0}var E=i.querySelectorAll("style");o.call(E,function(t){t.textContent+=""}),e.parentNode.replaceChild(i,e),delete s[s.indexOf(e)],e=null,l++,u(i)}))},g=function(t,e,r){e=e||{};var n=e.evalScripts||"always",i=e.pngFallback||!1,a=e.each;if(void 0!==t.length){var l=0;o.call(t,function(e){h(e,n,i,function(e){a&&"function"==typeof a&&a(e),r&&t.length===++l&&r(l)})})}else t?h(t,n,i,function(e){a&&"function"==typeof a&&a(e),r&&r(1),t=null}):r&&r(0)};"object"==typeof module&&"object"==typeof module.exports?module.exports=exports=g:"function"==typeof define&&define.amd?define(function(){return g}):"object"==typeof t&&(t.SVGInjector=g)}(window,document);
</code></pre>
<p>This is the code I have in my custom.js file that calls the script. I have tried placing it directly in the file and within document ready, and in both instances the blinking/shifting still happened:</p>
<h3>The SVGInjector js call (inside the enqueued 'custom' js file)</h3>
<pre><code>// For testing in IE8
if (!window.console){ console = {log: function() {}}; };
// Elements to inject
var mySVGsToInject = document.querySelectorAll('img.inject-me');
// Options
var injectorOptions = {
evalScripts: 'once',
pngFallback: 'assets/png',
each: function (svg) {
// Callback after each SVG is injected
if (svg) console.log('SVG injected: ' + svg.getAttribute('id'));
}
};
// Trigger the injection
SVGInjector(mySVGsToInject, injectorOptions, function (totalSVGsInjected) {
// Callback after all SVGs are injected
console.log('We injected ' + totalSVGsInjected + ' SVG(s)!');
});
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 247373,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p><code>get_theme_mod()</code> has a second parameter where you can set the default value, the value to use if t... | 2016/11/25 | [
"https://wordpress.stackexchange.com/questions/247402",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
] | I am enqueuing some javascript that injects SVGs into my page's DOM (called [SVGInjector](https://github.com/iconic/SVGInjector)); it works great except for one thing: there is an undesirable "blink"/shift of elements on my screen where the injected elements are placed upon loading. Apparently this blink has a name I found months after asking the question, it is called the Flash of Unstyled Content (or FOUC) and even has its own [Wiki](https://en.wikipedia.org/wiki/Flash_of_unstyled_content).
The reason for this shift seems pretty clear: the page's other elements are apparently drawn *before* the js that injects the SVGs runs, and then, once they are inserted, the page changes to accommodate the added SVGs. I mentioned it here in an answer to my own question that I asked yesterday: <https://wordpress.stackexchange.com/a/247315/105196>
How to prevent element movement due to late injection?
======================================================
I am hoping someone can tell me how to prevent this blinking/shift. I believe the solution would entail either 1) delaying the drawing of the page's other elements until after the SVG is injected via the enqueued js or 2) making the js run earlier, but I'm not sure. Even if this is what I need to do, I'm not sure how to do it.
### Some clues, perhaps
There is some info here about running js before loading the whole page, <https://stackoverflow.com/questions/2920129/can-i-run-javascript-before-the-whole-page-is-loaded>, but it is about web-coding, in general, not WordPress specific. I don't understand enough about WP and enqueuing to figure out how to adapt these solutions.
The Code
========
### How I enqueued the js in functions.php:
```
function mytheme_enqueue_front_page_scripts() {
if( is_front_page() )
{
wp_enqueue_script( 'injectSVG', get_stylesheet_directory_uri() . '/js/svg-injector.min.js', array( 'jquery' ), null, true );
wp_enqueue_script( 'custom', get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ), null, true );
}
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_front_page_scripts' );
```
The problem may lie in the SVGinjector script itself, it might specifically have instructions to wait until the other elements are drawn. You can take a look at it here if you think it might be the cause:
### The SVGInjector js script (enqueued as 'injectSVG')
```
!function(t,e){"use strict";function r(t){t=t.split(" ");for(var e={},r=t.length,n=[];r--;)e.hasOwnProperty(t[r])||(e[t[r]]=1,n.unshift(t[r]));return n.join(" ")}var n="file:"===t.location.protocol,i=e.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1"),o=Array.prototype.forEach||function(t,e){if(void 0===this||null===this||"function"!=typeof t)throw new TypeError;var r,n=this.length>>>0;for(r=0;n>r;++r)r in this&&t.call(e,this[r],r,this)},a={},l=0,s=[],u=[],c={},f=function(t){return t.cloneNode(!0)},p=function(t,e){u[t]=u[t]||[],u[t].push(e)},d=function(t){for(var e=0,r=u[t].length;r>e;e++)!function(e){setTimeout(function(){u[t][e](f(a[t]))},0)}(e)},v=function(e,r){if(void 0!==a[e])a[e]instanceof SVGSVGElement?r(f(a[e])):p(e,r);else{if(!t.XMLHttpRequest)return r("Browser does not support XMLHttpRequest"),!1;a[e]={},p(e,r);var i=new XMLHttpRequest;i.onreadystatechange=function(){if(4===i.readyState){if(404===i.status||null===i.responseXML)return r("Unable to load SVG file: "+e),n&&r("Note: SVG injection ajax calls do not work locally without adjusting security setting in your browser. Or consider using a local webserver."),r(),!1;if(!(200===i.status||n&&0===i.status))return r("There was a problem injecting the SVG: "+i.status+" "+i.statusText),!1;if(i.responseXML instanceof Document)a[e]=i.responseXML.documentElement;else if(DOMParser&&DOMParser instanceof Function){var t;try{var o=new DOMParser;t=o.parseFromString(i.responseText,"text/xml")}catch(l){t=void 0}if(!t||t.getElementsByTagName("parsererror").length)return r("Unable to parse SVG file: "+e),!1;a[e]=t.documentElement}d(e)}},i.open("GET",e),i.overrideMimeType&&i.overrideMimeType("text/xml"),i.send()}},h=function(e,n,a,u){var f=e.getAttribute("data-src")||e.getAttribute("src");if(!/\.svg/i.test(f))return void u("Attempted to inject a file with a non-svg extension: "+f);if(!i){var p=e.getAttribute("data-fallback")||e.getAttribute("data-png");return void(p?(e.setAttribute("src",p),u(null)):a?(e.setAttribute("src",a+"/"+f.split("/").pop().replace(".svg",".png")),u(null)):u("This browser does not support SVG and no PNG fallback was defined."))}-1===s.indexOf(e)&&(s.push(e),e.setAttribute("src",""),v(f,function(i){if("undefined"==typeof i||"string"==typeof i)return u(i),!1;var a=e.getAttribute("id");a&&i.setAttribute("id",a);var p=e.getAttribute("title");p&&i.setAttribute("title",p);var d=[].concat(i.getAttribute("class")||[],"injected-svg",e.getAttribute("class")||[]).join(" ");i.setAttribute("class",r(d));var v=e.getAttribute("style");v&&i.setAttribute("style",v);var h=[].filter.call(e.attributes,function(t){return/^data-\w[\w\-]*$/.test(t.name)});o.call(h,function(t){t.name&&t.value&&i.setAttribute(t.name,t.value)});var g,m,b,y,A,w={clipPath:["clip-path"],"color-profile":["color-profile"],cursor:["cursor"],filter:["filter"],linearGradient:["fill","stroke"],marker:["marker","marker-start","marker-mid","marker-end"],mask:["mask"],pattern:["fill","stroke"],radialGradient:["fill","stroke"]};Object.keys(w).forEach(function(t){g=t,b=w[t],m=i.querySelectorAll("defs "+g+"[id]");for(var e=0,r=m.length;r>e;e++){y=m[e].id,A=y+"-"+l;var n;o.call(b,function(t){n=i.querySelectorAll("["+t+'*="'+y+'"]');for(var e=0,r=n.length;r>e;e++)n[e].setAttribute(t,"url(#"+A+")")}),m[e].id=A}}),i.removeAttribute("xmlns:a");for(var x,S,k=i.querySelectorAll("script"),j=[],G=0,T=k.length;T>G;G++)S=k[G].getAttribute("type"),S&&"application/ecmascript"!==S&&"application/javascript"!==S||(x=k[G].innerText||k[G].textContent,j.push(x),i.removeChild(k[G]));if(j.length>0&&("always"===n||"once"===n&&!c[f])){for(var M=0,V=j.length;V>M;M++)new Function(j[M])(t);c[f]=!0}var E=i.querySelectorAll("style");o.call(E,function(t){t.textContent+=""}),e.parentNode.replaceChild(i,e),delete s[s.indexOf(e)],e=null,l++,u(i)}))},g=function(t,e,r){e=e||{};var n=e.evalScripts||"always",i=e.pngFallback||!1,a=e.each;if(void 0!==t.length){var l=0;o.call(t,function(e){h(e,n,i,function(e){a&&"function"==typeof a&&a(e),r&&t.length===++l&&r(l)})})}else t?h(t,n,i,function(e){a&&"function"==typeof a&&a(e),r&&r(1),t=null}):r&&r(0)};"object"==typeof module&&"object"==typeof module.exports?module.exports=exports=g:"function"==typeof define&&define.amd?define(function(){return g}):"object"==typeof t&&(t.SVGInjector=g)}(window,document);
```
This is the code I have in my custom.js file that calls the script. I have tried placing it directly in the file and within document ready, and in both instances the blinking/shifting still happened:
### The SVGInjector js call (inside the enqueued 'custom' js file)
```
// For testing in IE8
if (!window.console){ console = {log: function() {}}; };
// Elements to inject
var mySVGsToInject = document.querySelectorAll('img.inject-me');
// Options
var injectorOptions = {
evalScripts: 'once',
pngFallback: 'assets/png',
each: function (svg) {
// Callback after each SVG is injected
if (svg) console.log('SVG injected: ' + svg.getAttribute('id'));
}
};
// Trigger the injection
SVGInjector(mySVGsToInject, injectorOptions, function (totalSVGsInjected) {
// Callback after all SVGs are injected
console.log('We injected ' + totalSVGsInjected + ' SVG(s)!');
});
```
Thanks! | `get_theme_mod()` has a second parameter where you can set the default value, the value to use if the option is not set.
So, if the default value is `"1"`, you can use:
```
get_theme_mod( 'display_header_image_title', '1' )
```
Then, if there is not value for `display_header_image_title` (no value in database), `"1"` is used. So, you could check the exact value:
```
if( get_theme_mod( 'display_header_image_title', '1' ) === '1' ) {
}
```
Or just true/false:
```
if( get_theme_mod( 'display_header_image_title', '1' ) ) {
}
``` |
247,409 | <p>I have a custom post type <strong><code>books</code></strong> and a custom taxonomy <strong><code>books-categories</code></strong>. <code>wp_insert_post()</code> and it works. How can i add a second taxonomy called <strong><code>location</code></strong>? This code doeasn't save my custom taxonomy called <strong><code>location</code></strong>.
Can anyone help me please?</p>
<pre><code><?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
$tags = $_POST['post_tags'];
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'draft', // Choose: publish, preview, future, draft, etc.
'post_type' => 'books' //'post',page' or use a custom post type if you want to
);
//save the new post
$pid = wp_insert_post($new_post);
//insert taxonomies
wp_set_post_terms( $pid, $_POST['cat'], 'books-categories', false );
wp_set_post_terms( $pid, $_POST['location'], 'location', false );
}
?>
<!-- New Post Form -->
<div id="postbox">
<form id="new_post" name="new_post" method="post" action="">
<!-- post name -->
<p><label for="title">Title</label><br />
<input type="text" id="title" value="" tabindex="1" size="20" name="title" />
</p>
<!-- post Category -->
<p><label for="Category">Category:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=books-categories' ); ?></p>
<!-- post Location -->
<p><label for="Location">Location:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=location' ); ?></p>
<!-- post Content -->
<p><label for="description">Content</label><br />
<textarea id="description" tabindex="3" name="description" cols="50" rows="6"></textarea>
</p>
<!-- post tags -->
<p><label for="post_tags">Tags:</label>
<input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" /></p>
<p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
</div>
</code></pre>
| [
{
"answer_id": 247417,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that you have two inputs both sending data with <code>name</code> of <code>cat</code>.</p>\n\n<p>... | 2016/11/25 | [
"https://wordpress.stackexchange.com/questions/247409",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107745/"
] | I have a custom post type **`books`** and a custom taxonomy **`books-categories`**. `wp_insert_post()` and it works. How can i add a second taxonomy called **`location`**? This code doeasn't save my custom taxonomy called **`location`**.
Can anyone help me please?
```
<?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
$tags = $_POST['post_tags'];
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'draft', // Choose: publish, preview, future, draft, etc.
'post_type' => 'books' //'post',page' or use a custom post type if you want to
);
//save the new post
$pid = wp_insert_post($new_post);
//insert taxonomies
wp_set_post_terms( $pid, $_POST['cat'], 'books-categories', false );
wp_set_post_terms( $pid, $_POST['location'], 'location', false );
}
?>
<!-- New Post Form -->
<div id="postbox">
<form id="new_post" name="new_post" method="post" action="">
<!-- post name -->
<p><label for="title">Title</label><br />
<input type="text" id="title" value="" tabindex="1" size="20" name="title" />
</p>
<!-- post Category -->
<p><label for="Category">Category:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=books-categories' ); ?></p>
<!-- post Location -->
<p><label for="Location">Location:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=location' ); ?></p>
<!-- post Content -->
<p><label for="description">Content</label><br />
<textarea id="description" tabindex="3" name="description" cols="50" rows="6"></textarea>
</p>
<!-- post tags -->
<p><label for="post_tags">Tags:</label>
<input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" /></p>
<p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
</div>
``` | **wp\_set\_post\_terms() function will only work on the native post type**.
For a taxonomy on a custom post type use [wp\_set\_object\_terms()](https://codex.wordpress.org/Function_Reference/wp_set_object_terms).
Change your code to:
```
wp_set_object_terms( $pid, $_POST['cat'], 'books-categories', false );
wp_set_object_terms( $pid, $_POST['location'], 'location', false );
``` |
247,411 | <p>I've setup checkbox controls in my theme Customizer to show/hide the Logo and Site Title when they are checked/unchecked. By default, I want the Logo to display and the Site Title to be hidden.</p>
<p>Everything is working as it should except the Site Title won't display in the live preview when the checkbox is checked, unless settings are saved in the Customizer first. However, the logo does display by default and disappears when unchecked. This leads me to believe there is a problem with the javascript and/or if statement for the Site Title.</p>
<p>This is the code I have in my template file:</p>
<pre><code><?php if( get_theme_mod( 'display_logo' , '1' ) == '1') { ?>
<?php if ( function_exists( 'the_custom_logo' ) && has_custom_logo() ) : ?>
<?php the_custom_logo(); ?>
<?php else : ?>
<h1 class="site-logo"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home" title="<?php bloginfo( 'name' ); ?> - <?php bloginfo( 'description' ); ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png" alt="<?php bloginfo( 'name' ); ?> - <?php bloginfo( 'description' ); ?>" width="100" height="50" /></a></h1>
<?php endif; ?>
<?php } ?>
<?php if( get_theme_mod( 'display_site_title' , '0' ) == '1') { ?>
<?php if ( is_front_page() && is_home() ) : ?>
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<?php else : ?>
<p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p>
<?php endif; ?>
<?php } ?>
</code></pre>
<p>This is the code I have in my customizer.php file:</p>
<pre><code>// Display Logo
$wp_customize->add_setting( 'display_logo', array(
'default' => true,
'transport' => 'postMessage'
) );
$wp_customize->add_control( 'display_logo', array(
'label' => __( 'Display Logo', 'myTheme' ),
'type' => 'checkbox'
) );
// Display Site Title
$wp_customize->add_setting( 'display_site_title', array(
'default' => false,
'transport' => 'postMessage'
) );
$wp_customize->add_control( 'display_site_title', array(
'label' => __( 'Display Site Title', 'myTheme' ),
'type' => 'checkbox'
) );
</code></pre>
<p>This is the code I have in my corresponding customizer.js file:</p>
<pre><code>// Display Logo
wp.customize( 'display_logo', function( value ) {
value.bind( function( to ) {
if ( true === to ) {
$( '.site-logo' ).removeClass( 'hidden' );
} else {
$( '.site-logo' ).addClass( 'hidden' );
}
});
});
// Display Site Title
wp.customize( 'display_site_title', function( value ) {
value.bind( function( to ) {
if ( true === to ) {
$( '.site-title' ).removeClass( 'hidden' );
} else {
$( '.site-title' ).addClass( 'hidden' );
}
});
});
</code></pre>
| [
{
"answer_id": 247417,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that you have two inputs both sending data with <code>name</code> of <code>cat</code>.</p>\n\n<p>... | 2016/11/25 | [
"https://wordpress.stackexchange.com/questions/247411",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
] | I've setup checkbox controls in my theme Customizer to show/hide the Logo and Site Title when they are checked/unchecked. By default, I want the Logo to display and the Site Title to be hidden.
Everything is working as it should except the Site Title won't display in the live preview when the checkbox is checked, unless settings are saved in the Customizer first. However, the logo does display by default and disappears when unchecked. This leads me to believe there is a problem with the javascript and/or if statement for the Site Title.
This is the code I have in my template file:
```
<?php if( get_theme_mod( 'display_logo' , '1' ) == '1') { ?>
<?php if ( function_exists( 'the_custom_logo' ) && has_custom_logo() ) : ?>
<?php the_custom_logo(); ?>
<?php else : ?>
<h1 class="site-logo"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home" title="<?php bloginfo( 'name' ); ?> - <?php bloginfo( 'description' ); ?>"><img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png" alt="<?php bloginfo( 'name' ); ?> - <?php bloginfo( 'description' ); ?>" width="100" height="50" /></a></h1>
<?php endif; ?>
<?php } ?>
<?php if( get_theme_mod( 'display_site_title' , '0' ) == '1') { ?>
<?php if ( is_front_page() && is_home() ) : ?>
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<?php else : ?>
<p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p>
<?php endif; ?>
<?php } ?>
```
This is the code I have in my customizer.php file:
```
// Display Logo
$wp_customize->add_setting( 'display_logo', array(
'default' => true,
'transport' => 'postMessage'
) );
$wp_customize->add_control( 'display_logo', array(
'label' => __( 'Display Logo', 'myTheme' ),
'type' => 'checkbox'
) );
// Display Site Title
$wp_customize->add_setting( 'display_site_title', array(
'default' => false,
'transport' => 'postMessage'
) );
$wp_customize->add_control( 'display_site_title', array(
'label' => __( 'Display Site Title', 'myTheme' ),
'type' => 'checkbox'
) );
```
This is the code I have in my corresponding customizer.js file:
```
// Display Logo
wp.customize( 'display_logo', function( value ) {
value.bind( function( to ) {
if ( true === to ) {
$( '.site-logo' ).removeClass( 'hidden' );
} else {
$( '.site-logo' ).addClass( 'hidden' );
}
});
});
// Display Site Title
wp.customize( 'display_site_title', function( value ) {
value.bind( function( to ) {
if ( true === to ) {
$( '.site-title' ).removeClass( 'hidden' );
} else {
$( '.site-title' ).addClass( 'hidden' );
}
});
});
``` | **wp\_set\_post\_terms() function will only work on the native post type**.
For a taxonomy on a custom post type use [wp\_set\_object\_terms()](https://codex.wordpress.org/Function_Reference/wp_set_object_terms).
Change your code to:
```
wp_set_object_terms( $pid, $_POST['cat'], 'books-categories', false );
wp_set_object_terms( $pid, $_POST['location'], 'location', false );
``` |
247,439 | <p>I've updated my plugin, <a href="https://wordpress.org/plugins/disable-blogging/" rel="nofollow noreferrer">Disable Blogging</a>, to the latest version which is available in the WordPress repository.</p>
<p>Everything works as it should. However, one of my users has encountered an error when updating my plugin.</p>
<blockquote>
<p><strong>Fatal error</strong>: Can’t use function return value in write context in <code>.../wp-content/plugins/disable-blogging/includes/functions-extra.php</code> on <em>line 74</em></p>
</blockquote>
<p>They run this plugin on two other sites that they own and there is no issue. The only difference is the PHP version:</p>
<ul>
<li>The one that has the <em>error</em> is a GoDaddy server and it might be <strong>PHP 5.4.45</strong></li>
<li>The others are on Digital Ocean and <strong>PHP 5.6.25</strong></li>
</ul>
<p>Looking into my source code, here's the referring code on line 74 that's part of a function:</p>
<pre><code>'meta' => array( 'class' => empty( get_avatar( get_current_user_id(), 28 ) ) ? '' : 'with-avatar', ),
</code></pre>
<p>But here is the full code to that function. This function simply removes the "Howdy" greeting in the admin bar.</p>
<pre><code>public function admin_greeting( $wp_admin_bar ) {
# Remove admin greeting in all languages
if ( 0 != get_current_user_id() ) {
$wp_admin_bar->add_menu( array(
'id' => 'my-account',
'parent' => 'top-secondary',
'title' => wp_get_current_user()->display_name . get_avatar( get_current_user_id(), 28 ),
'href' => get_edit_profile_url( get_current_user_id() ),
'meta' => array( 'class' => empty( get_avatar( get_current_user_id(), 28 ) ) ? '' : 'with-avatar', ),
) );
}
}
</code></pre>
<p>From my guess, this could be a compatibility issue with PHP 5.4? I've been developing the plugin on 5.6 and according to PHP, <a href="https://secure.php.net/supported-versions.php" rel="nofollow noreferrer">version 5.4 is no longer being supported</a>.</p>
<p>If thats the case, I'd like to have confirmation on that. This way I can relay that back to the user and even add a function to check the PHP version of any WordPress site before it's activated.</p>
| [
{
"answer_id": 247430,
"author": "LebCit",
"author_id": 102912,
"author_profile": "https://wordpress.stackexchange.com/users/102912",
"pm_score": 0,
"selected": false,
"text": "<p>You can learn about Template Hierarchy on the developer handbook\n<a href=\"https://developer.wordpress.org/... | 2016/11/25 | [
"https://wordpress.stackexchange.com/questions/247439",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | I've updated my plugin, [Disable Blogging](https://wordpress.org/plugins/disable-blogging/), to the latest version which is available in the WordPress repository.
Everything works as it should. However, one of my users has encountered an error when updating my plugin.
>
> **Fatal error**: Can’t use function return value in write context in `.../wp-content/plugins/disable-blogging/includes/functions-extra.php` on *line 74*
>
>
>
They run this plugin on two other sites that they own and there is no issue. The only difference is the PHP version:
* The one that has the *error* is a GoDaddy server and it might be **PHP 5.4.45**
* The others are on Digital Ocean and **PHP 5.6.25**
Looking into my source code, here's the referring code on line 74 that's part of a function:
```
'meta' => array( 'class' => empty( get_avatar( get_current_user_id(), 28 ) ) ? '' : 'with-avatar', ),
```
But here is the full code to that function. This function simply removes the "Howdy" greeting in the admin bar.
```
public function admin_greeting( $wp_admin_bar ) {
# Remove admin greeting in all languages
if ( 0 != get_current_user_id() ) {
$wp_admin_bar->add_menu( array(
'id' => 'my-account',
'parent' => 'top-secondary',
'title' => wp_get_current_user()->display_name . get_avatar( get_current_user_id(), 28 ),
'href' => get_edit_profile_url( get_current_user_id() ),
'meta' => array( 'class' => empty( get_avatar( get_current_user_id(), 28 ) ) ? '' : 'with-avatar', ),
) );
}
}
```
From my guess, this could be a compatibility issue with PHP 5.4? I've been developing the plugin on 5.6 and according to PHP, [version 5.4 is no longer being supported](https://secure.php.net/supported-versions.php).
If thats the case, I'd like to have confirmation on that. This way I can relay that back to the user and even add a function to check the PHP version of any WordPress site before it's activated. | First plugins are loaded, then templates.
Media is not loaded until called (afaik) from either a plugin or theme.
Widgets, enqueued scripts and CSS can be called from both plugins and templates so it depends where they are defined. |
247,447 | <p>I am working on a plugin that has a piece of meta data attached to each post. The fields are editable in a meta box on the post. This is all working fine.</p>
<p>I would like to prevent anyone from modifying the settings in meta box once the post has been published. By virtue of the application looking for this meta data, it doesn't make any sense for the meta data to change after publish.</p>
<p>So, is there any way to tell if a post has been published at least once? This way I can disable the controls in the meta box.</p>
| [
{
"answer_id": 247452,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 2,
"selected": true,
"text": "<p>We can do this by storing the value into postmeta when post is published first time. </p>\n\n<pre><code>function ... | 2016/11/26 | [
"https://wordpress.stackexchange.com/questions/247447",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107763/"
] | I am working on a plugin that has a piece of meta data attached to each post. The fields are editable in a meta box on the post. This is all working fine.
I would like to prevent anyone from modifying the settings in meta box once the post has been published. By virtue of the application looking for this meta data, it doesn't make any sense for the meta data to change after publish.
So, is there any way to tell if a post has been published at least once? This way I can disable the controls in the meta box. | We can do this by storing the value into postmeta when post is published first time.
```
function save_ispublished( $post_id ) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
$published_once = get_post_meta( $post_id, 'is_published', true );
// Check if 'is_published' meta value is empty.
if ( ! empty( $published_once ) ) {
$published_once = 'yes';
}
// store is_published value when first time published.
update_post_meta( $post_id, 'is_published', $published_once );
}
add_action( 'save_post', 'save_ispublished' );
```
you can check it by get the meta value.
```
$is_published = get_post_meta( $post_id, 'is_published', true );
if( $is_published == 'yes' ) {
/*
* Actions if post is already published atleast once.
*/
}
```
Hope this help ! |
247,450 | <p>I have built a plug in and it appears to hook in ok. It runs at least. However it loads very slowly. I have attached my console log results. It appears as though the base url is not correctly built in some cases. www.mydomain.com/wordpress/plugin is combining with /wp-includes/js/jquery/. These entries should be www.mydomain.com/wordpress/wp-includes/js/jquery/. I am also seeing that this is inconsistent, sometimes it is built just fine. So I am trying to track down the file where this is happening but I am a little lost. Any tips would help.</p>
<pre><code>GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/jquery.js?ver=1.12.4 (index):54
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1 404 (Not Found) (index):55
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/core.min.js?ver=1.11.4 (index):603
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/datepicker.min.js?ver=1.11.4 404 (Not Found) (index):604
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/widget.min.js?ver=1.11.4 (index):606
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/slider.min.js?ver=1.11.4 (index):608
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/mouse.min.js?ver=1.11.4 (index):607
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/button.min.js?ver=1.11.4 (index):609
GET https://www.example.com/wordpress/plugin/wp-includes/js/wp-embed.min.js?ver=4.5.3 (index):616
GET https://www.example.com/wordpress/pluginjs/wp-emoji-release.min.js?ver=4.5.3 (index):28
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/slider.min.js?ver=1.11.4 (index):608
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/button.min.js?ver=1.11.4 404 (Not Found) (index):609
GET https://www.example.com/wordpress/plugin/wp-includes/js/wp-embed.min.js?ver=4.5.3 404 (Not Found) (index):616
Uncaught TypeError: jQuery(...).tinyNav is not a function(…) TinyNav.js?ver=4.5.3:91
Google sync successful frontend_book.js:513
</code></pre>
| [
{
"answer_id": 247452,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 2,
"selected": true,
"text": "<p>We can do this by storing the value into postmeta when post is published first time. </p>\n\n<pre><code>function ... | 2016/11/26 | [
"https://wordpress.stackexchange.com/questions/247450",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82889/"
] | I have built a plug in and it appears to hook in ok. It runs at least. However it loads very slowly. I have attached my console log results. It appears as though the base url is not correctly built in some cases. www.mydomain.com/wordpress/plugin is combining with /wp-includes/js/jquery/. These entries should be www.mydomain.com/wordpress/wp-includes/js/jquery/. I am also seeing that this is inconsistent, sometimes it is built just fine. So I am trying to track down the file where this is happening but I am a little lost. Any tips would help.
```
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/jquery.js?ver=1.12.4 (index):54
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1 404 (Not Found) (index):55
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/core.min.js?ver=1.11.4 (index):603
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/datepicker.min.js?ver=1.11.4 404 (Not Found) (index):604
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/widget.min.js?ver=1.11.4 (index):606
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/slider.min.js?ver=1.11.4 (index):608
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/mouse.min.js?ver=1.11.4 (index):607
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/button.min.js?ver=1.11.4 (index):609
GET https://www.example.com/wordpress/plugin/wp-includes/js/wp-embed.min.js?ver=4.5.3 (index):616
GET https://www.example.com/wordpress/pluginjs/wp-emoji-release.min.js?ver=4.5.3 (index):28
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/slider.min.js?ver=1.11.4 (index):608
GET https://www.example.com/wordpress/plugin/wp-includes/js/jquery/ui/button.min.js?ver=1.11.4 404 (Not Found) (index):609
GET https://www.example.com/wordpress/plugin/wp-includes/js/wp-embed.min.js?ver=4.5.3 404 (Not Found) (index):616
Uncaught TypeError: jQuery(...).tinyNav is not a function(…) TinyNav.js?ver=4.5.3:91
Google sync successful frontend_book.js:513
``` | We can do this by storing the value into postmeta when post is published first time.
```
function save_ispublished( $post_id ) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
$published_once = get_post_meta( $post_id, 'is_published', true );
// Check if 'is_published' meta value is empty.
if ( ! empty( $published_once ) ) {
$published_once = 'yes';
}
// store is_published value when first time published.
update_post_meta( $post_id, 'is_published', $published_once );
}
add_action( 'save_post', 'save_ispublished' );
```
you can check it by get the meta value.
```
$is_published = get_post_meta( $post_id, 'is_published', true );
if( $is_published == 'yes' ) {
/*
* Actions if post is already published atleast once.
*/
}
```
Hope this help ! |
247,503 | <p>I'm getting a HTTP 500 Error on my website. Not sure what it could be. But when I refresh the page, everything works correctly. Here goes the exact error</p>
<pre><code>The www.brothas.online page isn’t working
</code></pre>
<p>www.brothas.online is currently unable to handle this request.
HTTP ERROR 500</p>
<p>Usually it happens when trying to login or access the back end of the website. Any help or questions would be much appreciated. Thanks</p>
| [
{
"answer_id": 247452,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 2,
"selected": true,
"text": "<p>We can do this by storing the value into postmeta when post is published first time. </p>\n\n<pre><code>function ... | 2016/11/27 | [
"https://wordpress.stackexchange.com/questions/247503",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107806/"
] | I'm getting a HTTP 500 Error on my website. Not sure what it could be. But when I refresh the page, everything works correctly. Here goes the exact error
```
The www.brothas.online page isn’t working
```
www.brothas.online is currently unable to handle this request.
HTTP ERROR 500
Usually it happens when trying to login or access the back end of the website. Any help or questions would be much appreciated. Thanks | We can do this by storing the value into postmeta when post is published first time.
```
function save_ispublished( $post_id ) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
$published_once = get_post_meta( $post_id, 'is_published', true );
// Check if 'is_published' meta value is empty.
if ( ! empty( $published_once ) ) {
$published_once = 'yes';
}
// store is_published value when first time published.
update_post_meta( $post_id, 'is_published', $published_once );
}
add_action( 'save_post', 'save_ispublished' );
```
you can check it by get the meta value.
```
$is_published = get_post_meta( $post_id, 'is_published', true );
if( $is_published == 'yes' ) {
/*
* Actions if post is already published atleast once.
*/
}
```
Hope this help ! |
247,504 | <p>I have used WPML multi currency for a while, but recently I turned it off and use the other currency plugin.</p>
<p>Most of the amount have converted correctly, but for some amount still remain at the default currency even after I changed to another one:</p>
<p>1) Booking cost from Woocommerce Booking plugin </p>
<p>2) Extra option cost and total cost from Extra options plugin</p>
<p>The amount is obtain using AJAX , from the actions: </p>
<p>1) wc_bookings_calculate_costs</p>
<p>2) tc_epo_bookings_calculate_costs</p>
<p>After some studies , I found the amount is calculate at :</p>
<p>wp-content/plugins/woocommerce-multilingual/compatibility/class-wcml-bookings.php</p>
<p>The code : <a href="https://github.com/wp-premium/woocommerce-multilingual/blob/master/compatibility/class-wcml-bookings.php" rel="nofollow noreferrer">https://github.com/wp-premium/woocommerce-multilingual/blob/master/compatibility/class-wcml-bookings.php</a>
(the wc_bookings_calculate_costs is refered at line 163, and it goes to the function filter_wc_booking_cost at line 731)</p>
<p>So, it is quite strange as I already disabled the multi currency in WPML settings. </p>
<p>I suspect at some where the code still goes to the WPML currency, how to fix that?</p>
<p>Thanks for helping. </p>
| [
{
"answer_id": 247838,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>First at all, I just use WPML one time and I really don't liked it.</p>\n\n<p>It comes to me, that you maybe l... | 2016/11/27 | [
"https://wordpress.stackexchange.com/questions/247504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88666/"
] | I have used WPML multi currency for a while, but recently I turned it off and use the other currency plugin.
Most of the amount have converted correctly, but for some amount still remain at the default currency even after I changed to another one:
1) Booking cost from Woocommerce Booking plugin
2) Extra option cost and total cost from Extra options plugin
The amount is obtain using AJAX , from the actions:
1) wc\_bookings\_calculate\_costs
2) tc\_epo\_bookings\_calculate\_costs
After some studies , I found the amount is calculate at :
wp-content/plugins/woocommerce-multilingual/compatibility/class-wcml-bookings.php
The code : <https://github.com/wp-premium/woocommerce-multilingual/blob/master/compatibility/class-wcml-bookings.php>
(the wc\_bookings\_calculate\_costs is refered at line 163, and it goes to the function filter\_wc\_booking\_cost at line 731)
So, it is quite strange as I already disabled the multi currency in WPML settings.
I suspect at some where the code still goes to the WPML currency, how to fix that?
Thanks for helping. | First at all, I just use WPML one time and I really don't liked it.
It comes to me, that you maybe leave some po/mo files in the `wp-content/languages/woocommerce-multilingual/` or wpml one.
I found on a [thread](https://wpml.org/forums/topic/how-to-get-wpml-to-use-mo-files/) saying
>
> 1. Visit WPML > Theme and plugin localization > select 'Translate using .mo files' > select Automatically load the theme's .mo file
> using 'load\_theme\_textdomain'. > Enter textdomain > Save
> 2. The translations for wordpress and the admin screen are those to be placed in wp-content/languages - Download these files here:
> <http://wpcentral.io/internationalization/>
> 3. Your theme's language should be put in a themes/awr-theme/languages/ directory
> 4. Finally the naming of this file must match the language options set on your site. If your using Spanish in it's without changing the
> locale setting, WPML is associating es\_ES.mo. You can review those
> options if you visit WPML > Languages > Site Languages > Edit
> Languages.
>
>
>
Why not, this will explain this ghost plugin behaviour !? As woocommerce-multiligual compatibility check for other plugin option... Add with some custom template files, translation string, that can be understood.
Depending on how you deactivate (and delete ?) the plugin, is it possible that some options settings of multi-currency plugins remains in your install ?
Are you sure that any code (yours or another plugin or theme) is not calling `class-wcml-bookings.php` directly (without is\_plugin\_active() ), and by this way reactivate some actions and filter ? But I really doubt about this fact, as the class is not initiate, all filter reference will br broken.
In case I'm wrong, about the filter you are talking about line 163
```
add_filter( 'get_post_metadata', array( $this, 'filter_wc_booking_cost' ), 10, 4 );
```
Did you try to remove it with `remove_filter()` ?
```
remove_filter('get_post_metadata', 10, 4);
```
Writing this I lean more on mo/po way than filter.
Hope it helps! |
247,507 | <p>What is the reason for using a style sheet header on page templates, where critcal values are assigned within a comments block in php, instead of just declaring constants, objects, or some other php structure?</p>
<p>The style sheet header is like this:</p>
<pre><code>/*
Theme Name: Twenty Fifteen Child
Theme URI: *
Description: Twenty Fifteen Child Theme
Author: John Doe
Author URI: *
Template: twentyfifteen
Version: 1.0.0
License: GNU General Public License v2 or later
License URI:*
Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
Text Domain: twenty-fifteen-child
*/
</code></pre>
<p>What is the advantage of the active code in the comments block over putting those values in an array, example below? Is there no php code that would be better than putting live values into the comments?</p>
<pre><code>$child_theme_definition=array();
$child_theme_definition['theme_name']='Twenty Fifteen Child';
$child_theme_definition['theme_uri']=''*;
$child_theme_definition['Description']='Twenty Fifteen Child Theme';
$child_theme_definition['Author']='John Doe';
$child_theme_definition['Author URI']=''*;
$child_theme_definition['Template']='twentyfifteen';
$child_theme_definition['Version']='1.0.0';
$child_theme_definition['License']='GNU General Public License v2 or later';
$child_theme_definition['License URI']=''*;
$child_theme_definition['Tags']='light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
Text Domain: twenty-fifteen-child';
</code></pre>
<p>*urls omitted because my new account is not allowed to include more than two urls in a post.</p>
| [
{
"answer_id": 247511,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>The headers have to be read without the files being executed. The files are parsed to extract the headers without ... | 2016/11/27 | [
"https://wordpress.stackexchange.com/questions/247507",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107811/"
] | What is the reason for using a style sheet header on page templates, where critcal values are assigned within a comments block in php, instead of just declaring constants, objects, or some other php structure?
The style sheet header is like this:
```
/*
Theme Name: Twenty Fifteen Child
Theme URI: *
Description: Twenty Fifteen Child Theme
Author: John Doe
Author URI: *
Template: twentyfifteen
Version: 1.0.0
License: GNU General Public License v2 or later
License URI:*
Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
Text Domain: twenty-fifteen-child
*/
```
What is the advantage of the active code in the comments block over putting those values in an array, example below? Is there no php code that would be better than putting live values into the comments?
```
$child_theme_definition=array();
$child_theme_definition['theme_name']='Twenty Fifteen Child';
$child_theme_definition['theme_uri']=''*;
$child_theme_definition['Description']='Twenty Fifteen Child Theme';
$child_theme_definition['Author']='John Doe';
$child_theme_definition['Author URI']=''*;
$child_theme_definition['Template']='twentyfifteen';
$child_theme_definition['Version']='1.0.0';
$child_theme_definition['License']='GNU General Public License v2 or later';
$child_theme_definition['License URI']=''*;
$child_theme_definition['Tags']='light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
Text Domain: twenty-fifteen-child';
```
\*urls omitted because my new account is not allowed to include more than two urls in a post. | The headers have to be read without the files being executed. The files are parsed to extract the headers without executing the php code they contain. |
247,522 | <p>I'm making a custom meta field for posts.</p>
<p>In the back-end, get_post_meta works fine and returns the value.</p>
<p>In the front-end, it returns NULL:</p>
<pre><code>$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field); // NULL
echo $my_custom_field // ''
</code></pre>
<p>Things I tried and looked into:</p>
<ol>
<li><p>my_custom_field gets written to the database with corresponding post_id, and everything seems fine.</p></li>
<li><p>Using hard-coded post ID gives the same result</p></li>
<li><p>Putting the call inside the loop gives the same result</p></li>
</ol>
<p><strong>QUESTION:</strong> Why get_post_meta returns NULL, how to fetch the actual value?</p>
<p><strong>EDIT:</strong> The field is right there in the database:</p>
<pre>
meta_id post_id meta_key meta_value
<br>
139 87 my_custom_field IT works!
</pre>
<p>The function arguments reference correct post_id and meta_key which I have checked multiple times, including hard-coding the arguments. </p>
<p>I have also tried to change the name of the meta_key as suggested in some other answer - didn't work.</p>
<p>Backend code is basically this tutorial <a href="https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/" rel="nofollow noreferrer">https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/</a></p>
<p><strong>EDIT 2:</strong></p>
<p>No errors in my logs.</p>
<p>Here is the complete front-end code which returns NULL instead of expected value:</p>
<pre><code>add_action( 'the_post', 'output_my_custom_field');
function output_my_custom_field() {
$post_id = get_the_ID();
if ( !empty( $post_id ) ) {
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field);
}
}
</code></pre>
<p><strong>EDIT 3:</strong> Regardless of the hook used (I tried various ones), or even calling a function without any hooks - it still returns NULL.</p>
| [
{
"answer_id": 248258,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>In a function context, <code>output_my_custom_field()</code> can not use template tag like <code>get_the_ID()<... | 2016/11/27 | [
"https://wordpress.stackexchange.com/questions/247522",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8652/"
] | I'm making a custom meta field for posts.
In the back-end, get\_post\_meta works fine and returns the value.
In the front-end, it returns NULL:
```
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field); // NULL
echo $my_custom_field // ''
```
Things I tried and looked into:
1. my\_custom\_field gets written to the database with corresponding post\_id, and everything seems fine.
2. Using hard-coded post ID gives the same result
3. Putting the call inside the loop gives the same result
**QUESTION:** Why get\_post\_meta returns NULL, how to fetch the actual value?
**EDIT:** The field is right there in the database:
```
meta_id post_id meta_key meta_value
139 87 my_custom_field IT works!
```
The function arguments reference correct post\_id and meta\_key which I have checked multiple times, including hard-coding the arguments.
I have also tried to change the name of the meta\_key as suggested in some other answer - didn't work.
Backend code is basically this tutorial <https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/>
**EDIT 2:**
No errors in my logs.
Here is the complete front-end code which returns NULL instead of expected value:
```
add_action( 'the_post', 'output_my_custom_field');
function output_my_custom_field() {
$post_id = get_the_ID();
if ( !empty( $post_id ) ) {
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field);
}
}
```
**EDIT 3:** Regardless of the hook used (I tried various ones), or even calling a function without any hooks - it still returns NULL. | Not 100% sure I understand the question or problem, but this ought to work, I think:
```
add_action( 'the_post', 'output_my_custom_field');
function output_my_custom_field( $post_object ) {
$post_id = $post_object->ID;
// why the conditional (and redundant !empty) ?
// if ( !empty($post_id) ) ) {
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field);
// see above
// }
}
``` |
247,530 | <p>I have a custom post type <strong><code>books</code></strong> and 3 custom taxonomies attached to <strong><code>books</code></strong>. The custom taxonomies are: <strong><code>books-categories</code></strong> , <strong><code>location</code></strong> , <strong><code>services_c</code></strong>. How should i edit my form to get my taxonomies work;
I'm trying to solve this for 3 days and but i can't. Can anyone help me please?</p>
<pre><code><?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
$tags = $_POST['post_tags'];
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'tags_input' => array($tags),
'post_status' => 'draft', // Choose: publish, preview, future, draft, etc.
'post_type' => 'books' //'post',page' or use a custom post type if you want to
);
//save the new post
$pid = wp_insert_post($new_post);
}
?>
<!-- New Post Form -->
<div id="postbox">
<form id="new_post" name="new_post" method="post" action="">
<!-- post name -->
<p><label for="title">Title</label><br />
<input type="text" id="title" value="" tabindex="1" size="20" name="title" />
</p>
<!-- post Category -->
<p><label for="Category">Category:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=books-categories' ); ?></p>
<!-- post Location -->
<p><label for="Location">Location:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=location' ); ?></p>
<!-- post Services -->
<p><label for="Services">Services:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=services_c' ); ?></p>
<!-- post Content -->
<p><label for="description">Content</label><br />
<textarea id="description" tabindex="3" name="description" cols="50" rows="6"></textarea>
</p>
<!-- post tags -->
<p><label for="post_tags">Tags:</label>
<input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" /></p>
<p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
</div>
</code></pre>
| [
{
"answer_id": 248258,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>In a function context, <code>output_my_custom_field()</code> can not use template tag like <code>get_the_ID()<... | 2016/11/27 | [
"https://wordpress.stackexchange.com/questions/247530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107745/"
] | I have a custom post type **`books`** and 3 custom taxonomies attached to **`books`**. The custom taxonomies are: **`books-categories`** , **`location`** , **`services_c`**. How should i edit my form to get my taxonomies work;
I'm trying to solve this for 3 days and but i can't. Can anyone help me please?
```
<?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
$tags = $_POST['post_tags'];
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'tags_input' => array($tags),
'post_status' => 'draft', // Choose: publish, preview, future, draft, etc.
'post_type' => 'books' //'post',page' or use a custom post type if you want to
);
//save the new post
$pid = wp_insert_post($new_post);
}
?>
<!-- New Post Form -->
<div id="postbox">
<form id="new_post" name="new_post" method="post" action="">
<!-- post name -->
<p><label for="title">Title</label><br />
<input type="text" id="title" value="" tabindex="1" size="20" name="title" />
</p>
<!-- post Category -->
<p><label for="Category">Category:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=books-categories' ); ?></p>
<!-- post Location -->
<p><label for="Location">Location:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=location' ); ?></p>
<!-- post Services -->
<p><label for="Services">Services:</label><br />
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=services_c' ); ?></p>
<!-- post Content -->
<p><label for="description">Content</label><br />
<textarea id="description" tabindex="3" name="description" cols="50" rows="6"></textarea>
</p>
<!-- post tags -->
<p><label for="post_tags">Tags:</label>
<input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" /></p>
<p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
</div>
``` | Not 100% sure I understand the question or problem, but this ought to work, I think:
```
add_action( 'the_post', 'output_my_custom_field');
function output_my_custom_field( $post_object ) {
$post_id = $post_object->ID;
// why the conditional (and redundant !empty) ?
// if ( !empty($post_id) ) ) {
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field);
// see above
// }
}
``` |
247,558 | <p>I have code in function and plugin widget, please see my code below.</p>
<p><code>function.php</code> //show count</p>
<pre><code>function hwd_post_views(){
$post_id = get_the_ID();
$count_key = 'post_views_count';
$n = get_post_meta($post_id, $count_key, true);
if ($n > 999999999) {
$n_format = number_format($n / 1000000000, 1) . 'B';
} else if ($n > 999999) {
$n_format = number_format($n / 1000000, 1) . 'M';
} else if ($n > 999) {
$n_format = number_format($n / 1000, 1) . 'K';
} else {
$n_format = $n;
} echo $n_format;}
</code></pre>
<p><code>Widget-pop.php</code> //Plugin Show Popular Post</p>
<pre><code>/**
* Plugin Name: Popular Posts Widget
*/
add_action( 'widgets_init', 'hwd_pop_load_widgets' );
function hwd_pop_load_widgets() {
register_widget( 'hwd_pop_widget' );
}
class hwd_pop_widget extends WP_Widget {
/**
* Widget setup.
*/
function hwd_pop_widget() {
/* Widget settings. */
$widget_ops = array( 'classname' => 'hwd_pop_widget', 'description' => __('A widget that displays a list of popular posts within a time period of your choice.', 'hwd-text') );
/* Widget control settings. */
$control_ops = array( 'width' => 250, 'height' => 300, 'id_base' => 'hwd_pop_widget' );
/* Create the widget. */
$this->__construct( 'hwd_pop_widget', __('HWD: Popular Posts Widget', 'hwd-text'), $widget_ops, $control_ops );
}
/**
* How to display the widget on the screen.
*/
function widget( $args, $instance ) {
extract( $args );
/* Our variables from the widget settings. */
global $post;
$title = apply_filters('widget_title', $instance['title'] );
$popular_days = $instance['popular_days'];
$number = $instance['number'];
/* Before widget (defined by themes). */
echo $before_widget;
/* Display the widget title if one was input (before and after defined by themes). */
if ( $title )
echo $before_title . $title . $after_title;
?>
<div id="terpopuler" class="terpopuler__row">
<ul class="terpopuler__wrap">
<?php $i = 0; $popular_days_ago = '$popular_days days ago'; $recent = new WP_Query(array( 'posts_per_page' => $number, 'orderby' => 'meta_value_num', 'order' => 'DESC', 'meta_key' => 'post_views_count', 'date_query' => array( array( 'after' => $popular_days_ago )) )); while($recent->have_posts()) : $recent->the_post(); ?>
<li class="terpopuler__item">
<a href="<?php the_permalink(); ?>" rel="bookmark">
<div class="terpopuler__num"><?php $i++; echo $i ?></div>
<div class="terpopuler__title">
<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
</div>
<?php $post_views = get_post_meta($post->ID, 'post_views_count', true); if ( $post_views >= 1) { ?>
<span class="terpopuler__info"><?php hwd_post_views(); ?> kali dibaca</span>
<?php } ?>
</a>
</li>
<?php endwhile; ?>
</ul>
</div><!--widget-terpopuler-->
<?php
/* After widget (defined by themes). */
echo $after_widget;
}
/**
* Update the widget settings.
*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
/* Strip tags for title and name to remove HTML (important for text inputs). */
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['popular_days'] = strip_tags( $new_instance['popular_days'] );
$instance['number'] = strip_tags( $new_instance['number'] );
return $instance;
}
function form( $instance ) {
/* Set up some default widget settings. */
$defaults = array( 'title' => 'Title', 'number' => 5, 'popular_days' => 30 );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<!-- Widget Title: Text Input -->
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:90%;" />
</p>
<!-- Number of days -->
<p>
<label for="<?php echo $this->get_field_id( 'popular_days' ); ?>">Number of days to use for Trending topics:</label>
<input id="<?php echo $this->get_field_id( 'popular_days' ); ?>" name="<?php echo $this->get_field_name( 'popular_days' ); ?>" value="<?php echo $instance['popular_days']; ?>" size="3" />
</p>
<!-- Number of posts -->
<p>
<label for="<?php echo $this->get_field_id( 'number' ); ?>">Number of posts to display:</label>
<input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" value="<?php echo $instance['number']; ?>" size="3" />
</p>
<?php
}
}
</code></pre>
<p>See picture </p>
<p><a href="https://i.stack.imgur.com/gOEIH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gOEIH.png" alt="here"></a></p>
<p>I no understand, how to fix it?</p>
<p><strong>UPDATE</strong></p>
<p>My question not answer. I include file <code>widget-pop.php</code> to file <code>function.php</code> in my theme child. </p>
<p>if localhost (Xampp) it's work. Please see my site radarsulselcom</p>
<p>Thank's</p>
| [
{
"answer_id": 248258,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>In a function context, <code>output_my_custom_field()</code> can not use template tag like <code>get_the_ID()<... | 2016/11/27 | [
"https://wordpress.stackexchange.com/questions/247558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106929/"
] | I have code in function and plugin widget, please see my code below.
`function.php` //show count
```
function hwd_post_views(){
$post_id = get_the_ID();
$count_key = 'post_views_count';
$n = get_post_meta($post_id, $count_key, true);
if ($n > 999999999) {
$n_format = number_format($n / 1000000000, 1) . 'B';
} else if ($n > 999999) {
$n_format = number_format($n / 1000000, 1) . 'M';
} else if ($n > 999) {
$n_format = number_format($n / 1000, 1) . 'K';
} else {
$n_format = $n;
} echo $n_format;}
```
`Widget-pop.php` //Plugin Show Popular Post
```
/**
* Plugin Name: Popular Posts Widget
*/
add_action( 'widgets_init', 'hwd_pop_load_widgets' );
function hwd_pop_load_widgets() {
register_widget( 'hwd_pop_widget' );
}
class hwd_pop_widget extends WP_Widget {
/**
* Widget setup.
*/
function hwd_pop_widget() {
/* Widget settings. */
$widget_ops = array( 'classname' => 'hwd_pop_widget', 'description' => __('A widget that displays a list of popular posts within a time period of your choice.', 'hwd-text') );
/* Widget control settings. */
$control_ops = array( 'width' => 250, 'height' => 300, 'id_base' => 'hwd_pop_widget' );
/* Create the widget. */
$this->__construct( 'hwd_pop_widget', __('HWD: Popular Posts Widget', 'hwd-text'), $widget_ops, $control_ops );
}
/**
* How to display the widget on the screen.
*/
function widget( $args, $instance ) {
extract( $args );
/* Our variables from the widget settings. */
global $post;
$title = apply_filters('widget_title', $instance['title'] );
$popular_days = $instance['popular_days'];
$number = $instance['number'];
/* Before widget (defined by themes). */
echo $before_widget;
/* Display the widget title if one was input (before and after defined by themes). */
if ( $title )
echo $before_title . $title . $after_title;
?>
<div id="terpopuler" class="terpopuler__row">
<ul class="terpopuler__wrap">
<?php $i = 0; $popular_days_ago = '$popular_days days ago'; $recent = new WP_Query(array( 'posts_per_page' => $number, 'orderby' => 'meta_value_num', 'order' => 'DESC', 'meta_key' => 'post_views_count', 'date_query' => array( array( 'after' => $popular_days_ago )) )); while($recent->have_posts()) : $recent->the_post(); ?>
<li class="terpopuler__item">
<a href="<?php the_permalink(); ?>" rel="bookmark">
<div class="terpopuler__num"><?php $i++; echo $i ?></div>
<div class="terpopuler__title">
<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
</div>
<?php $post_views = get_post_meta($post->ID, 'post_views_count', true); if ( $post_views >= 1) { ?>
<span class="terpopuler__info"><?php hwd_post_views(); ?> kali dibaca</span>
<?php } ?>
</a>
</li>
<?php endwhile; ?>
</ul>
</div><!--widget-terpopuler-->
<?php
/* After widget (defined by themes). */
echo $after_widget;
}
/**
* Update the widget settings.
*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
/* Strip tags for title and name to remove HTML (important for text inputs). */
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['popular_days'] = strip_tags( $new_instance['popular_days'] );
$instance['number'] = strip_tags( $new_instance['number'] );
return $instance;
}
function form( $instance ) {
/* Set up some default widget settings. */
$defaults = array( 'title' => 'Title', 'number' => 5, 'popular_days' => 30 );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<!-- Widget Title: Text Input -->
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:90%;" />
</p>
<!-- Number of days -->
<p>
<label for="<?php echo $this->get_field_id( 'popular_days' ); ?>">Number of days to use for Trending topics:</label>
<input id="<?php echo $this->get_field_id( 'popular_days' ); ?>" name="<?php echo $this->get_field_name( 'popular_days' ); ?>" value="<?php echo $instance['popular_days']; ?>" size="3" />
</p>
<!-- Number of posts -->
<p>
<label for="<?php echo $this->get_field_id( 'number' ); ?>">Number of posts to display:</label>
<input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" value="<?php echo $instance['number']; ?>" size="3" />
</p>
<?php
}
}
```
See picture
[](https://i.stack.imgur.com/gOEIH.png)
I no understand, how to fix it?
**UPDATE**
My question not answer. I include file `widget-pop.php` to file `function.php` in my theme child.
if localhost (Xampp) it's work. Please see my site radarsulselcom
Thank's | Not 100% sure I understand the question or problem, but this ought to work, I think:
```
add_action( 'the_post', 'output_my_custom_field');
function output_my_custom_field( $post_object ) {
$post_id = $post_object->ID;
// why the conditional (and redundant !empty) ?
// if ( !empty($post_id) ) ) {
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field);
// see above
// }
}
``` |
247,589 | <p>I have a very simple wordpress problem, but I'm still struggling to figure out the solution. I have an anchor tag, and I want it to open an image gallery in a lightbox (as the default behavior when user clicks on one of the images from the image gallery) on click.</p>
<p>The image gallery should be hidden otherwise, visible only when the user clicks "show gallery" link.</p>
<p>Here's the code:</p>
<pre><code>[gallery link="file" ids="163337,163336,163335,163334"]
<a href="#">View gallery</a>
</code></pre>
<p>Can someone help me please? How do I bind the two elements together? Is there any easy way like setting the class to the anchor tag and selector name to gallery tag (as X theme makes it easily done) or do I have to write the lightbox code from scratch? It would be highly appreciated.</p>
| [
{
"answer_id": 248258,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>In a function context, <code>output_my_custom_field()</code> can not use template tag like <code>get_the_ID()<... | 2016/11/17 | [
"https://wordpress.stackexchange.com/questions/247589",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have a very simple wordpress problem, but I'm still struggling to figure out the solution. I have an anchor tag, and I want it to open an image gallery in a lightbox (as the default behavior when user clicks on one of the images from the image gallery) on click.
The image gallery should be hidden otherwise, visible only when the user clicks "show gallery" link.
Here's the code:
```
[gallery link="file" ids="163337,163336,163335,163334"]
<a href="#">View gallery</a>
```
Can someone help me please? How do I bind the two elements together? Is there any easy way like setting the class to the anchor tag and selector name to gallery tag (as X theme makes it easily done) or do I have to write the lightbox code from scratch? It would be highly appreciated. | Not 100% sure I understand the question or problem, but this ought to work, I think:
```
add_action( 'the_post', 'output_my_custom_field');
function output_my_custom_field( $post_object ) {
$post_id = $post_object->ID;
// why the conditional (and redundant !empty) ?
// if ( !empty($post_id) ) ) {
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field);
// see above
// }
}
``` |
247,624 | <p>I made multiple custom search on my wordpress site to find post with category search. Like this:</p>
<pre><code> <select id="category-select" name="category-select">
<option value="6">Todo</option>
<option value="7">Spain</option>
<option value="8">Europe</option>
<option value="30">Rest of the World</option>
</select>
<input type="text" id="autoc-input" name="autoc-input" autocomplete="off" placeholder="">
</code></pre>
<p>My form sends correctly all the parameters, for example if i search Barcelona for the category Spain i got this url:</p>
<blockquote>
<p>?s=Barcelona&cat=7</p>
</blockquote>
<p>I can't get any result from this query, but if i search just for my input or category. With this i got all the post from the category on the search page:</p>
<blockquote>
<p>?s=cat=7</p>
</blockquote>
<p>And with this all the post that contains Barcelona.</p>
<blockquote>
<p>?s=Barcelona</p>
</blockquote>
<p>I can't find the issue to get the results with more than one parameter. How can i fix this?</p>
| [
{
"answer_id": 248258,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>In a function context, <code>output_my_custom_field()</code> can not use template tag like <code>get_the_ID()<... | 2016/11/28 | [
"https://wordpress.stackexchange.com/questions/247624",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/42606/"
] | I made multiple custom search on my wordpress site to find post with category search. Like this:
```
<select id="category-select" name="category-select">
<option value="6">Todo</option>
<option value="7">Spain</option>
<option value="8">Europe</option>
<option value="30">Rest of the World</option>
</select>
<input type="text" id="autoc-input" name="autoc-input" autocomplete="off" placeholder="">
```
My form sends correctly all the parameters, for example if i search Barcelona for the category Spain i got this url:
>
> ?s=Barcelona&cat=7
>
>
>
I can't get any result from this query, but if i search just for my input or category. With this i got all the post from the category on the search page:
>
> ?s=cat=7
>
>
>
And with this all the post that contains Barcelona.
>
> ?s=Barcelona
>
>
>
I can't find the issue to get the results with more than one parameter. How can i fix this? | Not 100% sure I understand the question or problem, but this ought to work, I think:
```
add_action( 'the_post', 'output_my_custom_field');
function output_my_custom_field( $post_object ) {
$post_id = $post_object->ID;
// why the conditional (and redundant !empty) ?
// if ( !empty($post_id) ) ) {
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field);
// see above
// }
}
``` |
247,645 | <p>I have one template file <code>videos.php</code> which has the following line of code in it (aswell as a load of HTML):</p>
<p><code><?php get_template_part('loop', 'feed-videos' ); ?></code></p>
<p>inside that template part, I have the following:</p>
<pre><code><?php $video = 'video-' . $post->ID; ?>
<?php get_template_part( 'include', 'modal-video' ); ?>
</code></pre>
<p>I would then like to be able to use the <code>$video</code> variable inside <code>include-modal-video.php</code>.</p>
<p>So at the top of <code>include-modal-video.php</code> I have:</p>
<pre><code><?php global $video; ?>
</code></pre>
<p>Further down that file, I have <code><h2>00: <?php echo $video; ?></h2></code></p>
<p>But I get nothing output from that line of code. All I see is the following indicator of where the value <em>should</em> be</p>
<blockquote>
<p>00</p>
</blockquote>
<p>Can anyone see what Im doing wrong?</p>
| [
{
"answer_id": 247646,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 4,
"selected": true,
"text": "<p>If you use <code>locate_template()</code> instead of <code>get_template_part()</code> you can use all variables i... | 2016/11/28 | [
"https://wordpress.stackexchange.com/questions/247645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have one template file `videos.php` which has the following line of code in it (aswell as a load of HTML):
`<?php get_template_part('loop', 'feed-videos' ); ?>`
inside that template part, I have the following:
```
<?php $video = 'video-' . $post->ID; ?>
<?php get_template_part( 'include', 'modal-video' ); ?>
```
I would then like to be able to use the `$video` variable inside `include-modal-video.php`.
So at the top of `include-modal-video.php` I have:
```
<?php global $video; ?>
```
Further down that file, I have `<h2>00: <?php echo $video; ?></h2>`
But I get nothing output from that line of code. All I see is the following indicator of where the value *should* be
>
> 00
>
>
>
Can anyone see what Im doing wrong? | If you use `locate_template()` instead of `get_template_part()` you can use all variables in that script:
```
include(locate_template('include-modal-video.php'));
```
Then, `<h2>00: <?php echo $video; ?></h2>` will work.
**UPDATE:**
Since WP version 5.5, you can pass arbitrary data to `get_template_part()` for use in the template - see the other answer below from @Denis Fedorov |
247,654 | <p>I have part search function in my WordPress website which uses dynamic dependent select box.</p>
<p>However, now I have the following problem:</p>
<p><strong>If only select the first one box, or select the first two boxes, and click the <code>Search</code> button, it successfully jumps to the result page.</strong></p>
<p><strong>However, if continuously select the third box, it jumps to a page with the same URL as the result page but the content of the homepage.</strong></p>
<p><strong>I check the Chrome Console and see this error:</strong></p>
<p><code>Failed to load resource: the server responded with a status of 404 (Not Found)</code></p>
<p>I have all the relative code below.</p>
<p><strong>1. font-end part of the select boxes:</strong></p>
<pre><code><form class="select-boxes" action="<?php echo site_url("/part-search-result/"); ?>" method="POST" target="_blank">
<?php include(__DIR__.'/inc/part-search.php'); ?>
</form>
</code></pre>
<p><strong>2. <code>part-search.php</code></strong></p>
<pre><code><?php
include( __DIR__.'/db-config.php' );
$query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
$rowCount = $query->num_rows;
?>
<select name="manufacturer" id="manufact" onchange="manufactText(this)">
<option value="">Select Manufacturer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
}
}else{
echo '<option value="">Manufacturer Not Available</option>';
}
?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
function manufactText(ddl) {
document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="type" id="type" onchange="typeText(this)">
<option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
function typeText(ddl) {
document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="year" id="year" onchange="yearText(this)">
<option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
function yearText(ddl) {
document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="model" id="model" onchange="modelText(this)">
<option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
function modelText(ddl) {
document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<input type="submit" name="search" id="search" value="Search">
<script type="text/javascript">
jQuery(function($) {
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'manufact_id='+manufactID,
success:function(html){
$('#type').html(html);
$('#year').html('<option value="">Select Type First</option>');
}
});
}else{
$('#type').html('<option value="">Select Manufact First</option>');
$('#year').html('<option value="">Select Type First</option>');
}
});
$('#type').on('change',function(){
var typeID = $(this).val();
if(typeID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'type_id='+typeID,
success:function(html){
$('#year').html(html);
$('#model').html('<option value="">Select Year First</option>');
}
});
}else{
$('#year').html('<option value="">Select Type First</option>');
$('#model').html('<option value="">Select Year First</option>');
}
});
$('#year').on('change',function(){
var yearID = $(this).val();
if(yearID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'year_id='+yearID,
success:function(html){
$('#model').html(html);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
</script>
</code></pre>
<p><strong>3. <code>ajax-data.php</code></strong></p>
<pre><code><?php
include( __DIR__.'/db-config.php' );
if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
$query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Type</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
}
}else{
echo '<option value="">Type Not Available</option>';
}
}
if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
$query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Year</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
}
}else{
echo '<option value="">Year Not Available</option>';
}
}
if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
$query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
}
}else{
echo '<option value="">Model Not Available</option>';
}
}
?>
</code></pre>
<p><strong>4. <code>part-search-result.php</code></strong></p>
<pre><code><?php
if (isset($_POST['search'])) {
$clauses = array();
if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
$clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
}
if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
$clauses[] = "`type` = '{$_POST['type_text']}'";
}
if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
$clauses[] = "`year` = '{$_POST['year_text']}'";
}
if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
$clauses[] = "`model` = '{$_POST['model_text']}'";
}
$where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
$sql = "SELECT * FROM `wp_products` ". $where;
$result = filterTable($sql);
} else {
$sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
$result = filterTable($sql);
}
function filterTable($sql) {
$con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$filter_Result = mysqli_query($con, $sql);
return $filter_Result;
}
?>
<?php get_header(); ?>
<div class="container">
<div id="products" class="row list-group">
<?php while ( $rows = mysqli_fetch_array($result) ): ?>
<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">
<div class="thumbnail">
<?php
echo '<img name="product-image" class="group list-group-image hvr-bob" src=' . $rows['image_url'] . ' width="400px" height="250px" alt="" />';
?>
<div class="caption">
<h4 class="group inner list-group-item-heading">
<?php
echo "Manufacturer:\t".$rows['manufacturer'].'<br>';
echo "Type:\t".$rows['type'].'<br>';
echo "Year:\t".$rows['year'].'<br>';
echo "Model:\t".$rows['model'].'<br>';
echo '<br>';
echo "Description:\t".$rows['description'].'<br>';
?>
</h4>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<?php get_footer(); ?>
</code></pre>
<p>I thought there might be problem with not using POST correctly in WordPress, I found a tutorial: <a href="https://www.sitepoint.com/handling-post-requests-the-wordpress-way/" rel="noreferrer">Handling POST Requests the WordPress Way</a></p>
<p>However, I already used <code>action</code> to jump to the result page, I have no idea how to solve my problem.</p>
| [
{
"answer_id": 264147,
"author": "Nate",
"author_id": 87380,
"author_profile": "https://wordpress.stackexchange.com/users/87380",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need any mySQL queries. WordPress's default search is submitting \"s\" with the URL. You can accomplis... | 2016/11/28 | [
"https://wordpress.stackexchange.com/questions/247654",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107752/"
] | I have part search function in my WordPress website which uses dynamic dependent select box.
However, now I have the following problem:
**If only select the first one box, or select the first two boxes, and click the `Search` button, it successfully jumps to the result page.**
**However, if continuously select the third box, it jumps to a page with the same URL as the result page but the content of the homepage.**
**I check the Chrome Console and see this error:**
`Failed to load resource: the server responded with a status of 404 (Not Found)`
I have all the relative code below.
**1. font-end part of the select boxes:**
```
<form class="select-boxes" action="<?php echo site_url("/part-search-result/"); ?>" method="POST" target="_blank">
<?php include(__DIR__.'/inc/part-search.php'); ?>
</form>
```
**2. `part-search.php`**
```
<?php
include( __DIR__.'/db-config.php' );
$query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
$rowCount = $query->num_rows;
?>
<select name="manufacturer" id="manufact" onchange="manufactText(this)">
<option value="">Select Manufacturer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
}
}else{
echo '<option value="">Manufacturer Not Available</option>';
}
?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
function manufactText(ddl) {
document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="type" id="type" onchange="typeText(this)">
<option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
function typeText(ddl) {
document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="year" id="year" onchange="yearText(this)">
<option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
function yearText(ddl) {
document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="model" id="model" onchange="modelText(this)">
<option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
function modelText(ddl) {
document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<input type="submit" name="search" id="search" value="Search">
<script type="text/javascript">
jQuery(function($) {
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'manufact_id='+manufactID,
success:function(html){
$('#type').html(html);
$('#year').html('<option value="">Select Type First</option>');
}
});
}else{
$('#type').html('<option value="">Select Manufact First</option>');
$('#year').html('<option value="">Select Type First</option>');
}
});
$('#type').on('change',function(){
var typeID = $(this).val();
if(typeID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'type_id='+typeID,
success:function(html){
$('#year').html(html);
$('#model').html('<option value="">Select Year First</option>');
}
});
}else{
$('#year').html('<option value="">Select Type First</option>');
$('#model').html('<option value="">Select Year First</option>');
}
});
$('#year').on('change',function(){
var yearID = $(this).val();
if(yearID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'year_id='+yearID,
success:function(html){
$('#model').html(html);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
</script>
```
**3. `ajax-data.php`**
```
<?php
include( __DIR__.'/db-config.php' );
if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
$query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Type</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
}
}else{
echo '<option value="">Type Not Available</option>';
}
}
if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
$query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Year</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
}
}else{
echo '<option value="">Year Not Available</option>';
}
}
if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
$query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
}
}else{
echo '<option value="">Model Not Available</option>';
}
}
?>
```
**4. `part-search-result.php`**
```
<?php
if (isset($_POST['search'])) {
$clauses = array();
if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
$clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
}
if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
$clauses[] = "`type` = '{$_POST['type_text']}'";
}
if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
$clauses[] = "`year` = '{$_POST['year_text']}'";
}
if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
$clauses[] = "`model` = '{$_POST['model_text']}'";
}
$where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
$sql = "SELECT * FROM `wp_products` ". $where;
$result = filterTable($sql);
} else {
$sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
$result = filterTable($sql);
}
function filterTable($sql) {
$con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$filter_Result = mysqli_query($con, $sql);
return $filter_Result;
}
?>
<?php get_header(); ?>
<div class="container">
<div id="products" class="row list-group">
<?php while ( $rows = mysqli_fetch_array($result) ): ?>
<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">
<div class="thumbnail">
<?php
echo '<img name="product-image" class="group list-group-image hvr-bob" src=' . $rows['image_url'] . ' width="400px" height="250px" alt="" />';
?>
<div class="caption">
<h4 class="group inner list-group-item-heading">
<?php
echo "Manufacturer:\t".$rows['manufacturer'].'<br>';
echo "Type:\t".$rows['type'].'<br>';
echo "Year:\t".$rows['year'].'<br>';
echo "Model:\t".$rows['model'].'<br>';
echo '<br>';
echo "Description:\t".$rows['description'].'<br>';
?>
</h4>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<?php get_footer(); ?>
```
I thought there might be problem with not using POST correctly in WordPress, I found a tutorial: [Handling POST Requests the WordPress Way](https://www.sitepoint.com/handling-post-requests-the-wordpress-way/)
However, I already used `action` to jump to the result page, I have no idea how to solve my problem. | To create your own independent search functionality, follow these steps.
**1-** You need a form to send the data for you. This is a simple form that can do this for you:
```
<form method="post" name="car-select" action="<?php echo site_url('/my-page/'); ?>">
<select name="make">
<option value="benz">Benz</option>
<option value="bmw">BMW</option>
<option value="audi">Audi</option>
</select>
<select name="type">
<option value="sedan">Sedan</option>
<option value="coupe">Coupe</option>
</select>
<input type="submit" value="Find my dream car!"/>
</form>
```
Which `/my-page/` is the slug for the page we are going to create later.
**2-** A function to handle the search results. Take a look at this basic function that searches the cars based on the entered values:
```
function my_custom_search() {
$car_make = $_POST['make'];
$car_type = $_POST['type'];
$car_query = new WP_Query ( array (
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array (
'taxonomy' => 'car_make',
'field' => 'slug',
'terms' => $car_make,
),
array (
'taxonomy' => 'car_type',
'field' => 'slug',
'terms' => $car_type,
),
),
));
if ($car_query->have_posts) {
while($car_query->have_posts()){
$car_query->the_post();
get_template_part('WHATEVER TEMPLATE YOU WANT TO USE');
}
}
// Pagination goes here
}
```
**3-** A page to show your search results. Remember the slug in the first requirement? Create a page in your template's directory and name it like `page-my-search-template.php`. Then include this function in your new page template, wherever you wish:
`my_custom_search();`
You should then create a page with `my-page` slug (the one in the form's action), using the template you just made.
Now, every submission of the form will trigger a search query and display the results in your very own search template!
**WAIT !! I want my pagination !!**
You can implement your own pagination in the search function, however i recommend using [WP-PageNavi](https://wordpress.org/plugins/wp-pagenavi/) for those who don't have enough skill to write a pagination script. Install the plugin, and set the query like this:
`wp_pagenavi(array( 'query' => $car_query ));`
This way you have a pagination for your custom search page, nice and easy. |
247,680 | <p>I have categories the names of which are 1 to 25. But the WordPress ordering system doesn't work correctly. It orders them as 1,10,11,12,13...2,21,22,23,24,25. I don't want to add 0 to 1-9 numbers. How can I fix this issue? </p>
<p>This is my code:</p>
<pre><code><li class="categoriesx <?php echo print_category_slug( get_the_category( $post->ID) ); ?>"
data-category="<?php echo print_category_slug( get_the_category( $post->ID) ); ?>">
</code></pre>
| [
{
"answer_id": 247682,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress will order your categories alphabetically, which leads to the result you get. You want to order them n... | 2016/11/28 | [
"https://wordpress.stackexchange.com/questions/247680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106214/"
] | I have categories the names of which are 1 to 25. But the WordPress ordering system doesn't work correctly. It orders them as 1,10,11,12,13...2,21,22,23,24,25. I don't want to add 0 to 1-9 numbers. How can I fix this issue?
This is my code:
```
<li class="categoriesx <?php echo print_category_slug( get_the_category( $post->ID) ); ?>"
data-category="<?php echo print_category_slug( get_the_category( $post->ID) ); ?>">
``` | Based on the research I've done on this, using term meta data is a better all around approach to ordering terms.
However, I was able come up with this snippet which does sort the terms by their name, numerically:
```
add_filter( 'terms_clauses', 'wpse247680_terms_clauses', 10, 3 );
function wpse247680_terms_clauses( $pieces, $taxonomies, $args ) {
// Bail if we are not looking at the right taxonomy, 'category' in this case.
if ( ! in_array( 'category', $taxonomies ) ) {
return $pieces;
}
// Casts the term name to an integer
// Idea derrived from similar idea using posts here: https://www.fldtrace.com/custom-post-types-numeric-title-order
$pieces['orderby'] = 'ORDER BY (t.name+0) ';
return $pieces;
}
```
Here's a screenshot showing this in action in the admin area. For testing, I created a new taxonomy named 'numeral', and created the terms in an arbitrary order. When the code posted above is used, the terms will be ordered numerically.
[](https://i.stack.imgur.com/GHZfc.png) |
247,685 | <p>I have a code which wraps every 4 posts in div. How can I adapt it to wrap every month posts in div.</p>
<pre><code><?php
$args = array(
'post_type' => 'posts',
'posts_per_page' => -1,
'order' => 'DESC'
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
$counter = 0;
while ($the_query->have_posts()) : $the_query->the_post();
if ($counter % 4 == 0) :
echo $counter > 0 ? "</div>" : "";
echo "<div class='row'>";
endif;
?>
<div class="col-3">
<?php the_title(); ?>
</div>
<?php
$counter++;
endwhile;
endif;
wp_reset_postdata();
?>
</code></pre>
| [
{
"answer_id": 247771,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 3,
"selected": true,
"text": "<pre><code>$last_month = null;\n\nwhile ( $the_query->have_posts() ) :\n $the_query->the_post();\n ... | 2016/11/28 | [
"https://wordpress.stackexchange.com/questions/247685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40822/"
] | I have a code which wraps every 4 posts in div. How can I adapt it to wrap every month posts in div.
```
<?php
$args = array(
'post_type' => 'posts',
'posts_per_page' => -1,
'order' => 'DESC'
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
$counter = 0;
while ($the_query->have_posts()) : $the_query->the_post();
if ($counter % 4 == 0) :
echo $counter > 0 ? "</div>" : "";
echo "<div class='row'>";
endif;
?>
<div class="col-3">
<?php the_title(); ?>
</div>
<?php
$counter++;
endwhile;
endif;
wp_reset_postdata();
?>
``` | ```
$last_month = null;
while ( $the_query->have_posts() ) :
$the_query->the_post();
$the_month = get_the_time( 'Ym' ); // e.g. 201611
if ( $last_month !== $the_month ) {
if ( $last_month !== null ) {
// Close previously opened <div class="row" />
echo '</div>';
}
echo '<div class="row">';
}
$last_month = $the_month;
?>
<div class="col-3">
<?php the_title(); ?>
</div>
<?php
if ( $the_query->current_post + 1 === $the_query->post_count ) {
// Last item, always close the div
echo '</div>';
}
endwhile;
``` |
247,699 | <p>I am looking for the font used in Wordpress, in the Customizer, describing what theme you are using see my graphic.
<a href="https://i.stack.imgur.com/3Mo6e.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Mo6e.jpg" alt="Font used in Customizer"></a></p>
| [
{
"answer_id": 247700,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>As of core version 4.6 WP went from web fonts back to using system fonts:</p>\n\n<blockquote>\n <p>As such, the fo... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247699",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107909/"
] | I am looking for the font used in Wordpress, in the Customizer, describing what theme you are using see my graphic.
[](https://i.stack.imgur.com/3Mo6e.jpg) | As of core version 4.6 WP went from web fonts back to using system fonts:
>
> As such, the font stack includes the following:
>
>
> * -apple-system for Safari (iOS & macOS) and Firefox macOS
> * BlinkMacSystemFont for Chrome macOS
> * Segoe UI for Windows
> * Roboto for Android and Chrome OS
> * Oxygen-Sans for KDE
> * Ubuntu for Ubuntu
> * Cantarell for GNOME
> * Helvetica Neue for versions of macOS prior to 10.11
> * sans-serif, the standard fallback
>
>
> <https://make.wordpress.org/core/2016/07/07/native-fonts-in-4-6/>
>
>
>
And exact technical expression/order in CSS as of right now is:
```
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
```
So the actual font you are seeing is highly specific to the system you are looking at it on. You should just use the browser debug tools to check which specific font is being used in the case you are interested in. |
247,708 | <p>Like the title suggests, I'm not too sure how to change the version of a .css file in my theme. At the moment the .css versioning is like this: </p>
<pre><code><link rel='stylesheet' id='xxxx' href='https://www. site css/ styles.css?ver=4.6.1' type='text/css' media='all' />
</code></pre>
<p>Is there a script that I need to run - where should I be looking to make the version 4.6.2 as per above?</p>
| [
{
"answer_id": 247709,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 5,
"selected": true,
"text": "<p>The fourth argument, <code>$ver</code> for <a href=\"https://developer.wordpress.org/reference/functions/wp_... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] | Like the title suggests, I'm not too sure how to change the version of a .css file in my theme. At the moment the .css versioning is like this:
```
<link rel='stylesheet' id='xxxx' href='https://www. site css/ styles.css?ver=4.6.1' type='text/css' media='all' />
```
Is there a script that I need to run - where should I be looking to make the version 4.6.2 as per above? | The fourth argument, `$ver` for [`wp_enqueue_style()`](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) allows you to set the version:
```
wp_enqueue_style( string $handle,
string $src = false,
array $deps = array(),
string|bool|null $ver = false,
string $media = 'all' );
```
Per the docs:
>
> **$ver** (string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query
> string for cache busting purposes. If version is set to false, a
> version number is automatically added equal to current installed
> WordPress version. If set to null, no version is added. Default value:
> `false`
>
>
> |
247,711 | <p>I'm learning from a plugin development course, and encountered two different internationalization functions:</p>
<pre><code><?php __('Newsletter Subscriber', 'ns_domain'); ?>
</code></pre>
<p>&</p>
<pre><code><?php _e('Title:'); ?>
</code></pre>
<p>I cannot find any reference information on when to use each one of these.</p>
<p>Can you point me in the right direction to learn more about these please?</p>
| [
{
"answer_id": 247712,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/_2\" rel=\"nofollow noreferrer\"><code>__()</code><... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247711",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
] | I'm learning from a plugin development course, and encountered two different internationalization functions:
```
<?php __('Newsletter Subscriber', 'ns_domain'); ?>
```
&
```
<?php _e('Title:'); ?>
```
I cannot find any reference information on when to use each one of these.
Can you point me in the right direction to learn more about these please? | [`__()`](https://codex.wordpress.org/Function_Reference/_2) "Retrieves the translated string from the translate() function" without echoing. `_e()` does the same thing but echos the output.
For more information, take a look at these help articles:
* [Internationalization](https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/)
* [Localization](https://developer.wordpress.org/plugins/internationalization/localization/)
* [**How to Internationalize Your Plugin**](https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/)
* [Internationalization Security](https://developer.wordpress.org/plugins/internationalization/security/) |
247,729 | <p>I have written a functionality like super admin can put user accounts on "hold". I have to make sure the user account which put his account on hold unable to login. The problem here is the user is able to login if still his account is on hold. I am using a 'custom user meta' field called 'holdUser' while super admin put a user on hold. While user login I am using the wordpress's wp-login action, how to edit wp-login action so that a user cannot login based on a custom user meta field in wordpress. While user account is put on hold I am updating the 'user meta' like below:</p>
<pre><code>if(isset($_GET['user_id']) && ($_GET['action']=='hold'))
{
update_user_meta( $_GET['user_id'], 'holdUser',1 );
wp_mail($email_to, $subject, $content,$headers);
}
</code></pre>
<p>My Login form has the following code:</p>
<pre><code><form method="post" action="'.$this->SiteUrl.'wp-login.php">
<input type="text" id="user_login" name="log">
<input type="password" name="pwd">
<button target="" class="submit">Login</button>
</form>
</code></pre>
<p>My Question here is how to edit 'wp-login.php' hook based on a user_meta field 'holdUser' if its value is 1 then not to login that user.?</p>
<p>Update: I wrote a separate hook if user login fails like below:</p>
<pre><code>add_action( 'wp_login_failed', 'my_front_end_login_fail' );
function my_front_end_login_fail( $username ) {
$referrer = $_SERVER['HTTP_REFERER'];
if( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') )
{
if ( !strstr($referrer,'/?actiont=failed') )
{
wp_redirect( $referrer . '/?actiont=failed&message=authentication-failed' );
}
else
{
wp_redirect( $referrer );
}
exit;
}
}
</code></pre>
<p>how can I get that on hold message from 'on_hold_error' hook?</p>
| [
{
"answer_id": 247731,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <code>wp_authenticate_user</code> filter and return a <code>WP_Error</code> to stop the login.</p>\n\n<p... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247729",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] | I have written a functionality like super admin can put user accounts on "hold". I have to make sure the user account which put his account on hold unable to login. The problem here is the user is able to login if still his account is on hold. I am using a 'custom user meta' field called 'holdUser' while super admin put a user on hold. While user login I am using the wordpress's wp-login action, how to edit wp-login action so that a user cannot login based on a custom user meta field in wordpress. While user account is put on hold I am updating the 'user meta' like below:
```
if(isset($_GET['user_id']) && ($_GET['action']=='hold'))
{
update_user_meta( $_GET['user_id'], 'holdUser',1 );
wp_mail($email_to, $subject, $content,$headers);
}
```
My Login form has the following code:
```
<form method="post" action="'.$this->SiteUrl.'wp-login.php">
<input type="text" id="user_login" name="log">
<input type="password" name="pwd">
<button target="" class="submit">Login</button>
</form>
```
My Question here is how to edit 'wp-login.php' hook based on a user\_meta field 'holdUser' if its value is 1 then not to login that user.?
Update: I wrote a separate hook if user login fails like below:
```
add_action( 'wp_login_failed', 'my_front_end_login_fail' );
function my_front_end_login_fail( $username ) {
$referrer = $_SERVER['HTTP_REFERER'];
if( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') )
{
if ( !strstr($referrer,'/?actiont=failed') )
{
wp_redirect( $referrer . '/?actiont=failed&message=authentication-failed' );
}
else
{
wp_redirect( $referrer );
}
exit;
}
}
```
how can I get that on hold message from 'on\_hold\_error' hook? | ```
function myplugin_authenticate_on_hold($user)
{
// username and password are correct
if ($user instanceof WP_User) {
$on_hold = get_user_meta($user->ID, 'is_on_hold', true);
if ($on_hold) {
return new WP_Error('on_hold_error', 'You are on hold');
}
}
return $user;
}
add_filter('authenticate', 'myplugin_authenticate_on_hold', 21);
```
The priority needs to be 21, as `wp_authenticate_username_password` and `wp_authenticate_email_password` are priority 20. They return an object of the type `WP_User` if they could authenticate the user. So if the user is authenticated, check if he is on hold. If he is, show the user an error.
Edit: why aren't you using the default login form? |
247,730 | <p>How can I retrieve the current URL (whether homepage, archive, post type archive, category archive, etc) but always <strong>without</strong> the <code>/page/{pagenum}/</code> part if it's present? So, if the real URL is: </p>
<p><code>example.com/category/uncategorized/</code> </p>
<p>OR</p>
<p><code>example.com/category/uncategorized/page/2/</code></p>
<p>then the return value will always be </p>
<p><code>example.com/category/uncategorized/</code></p>
| [
{
"answer_id": 247732,
"author": "Fabian Marz",
"author_id": 77421,
"author_profile": "https://wordpress.stackexchange.com/users/77421",
"pm_score": -1,
"selected": false,
"text": "<p>While this question was already answered <a href=\"https://wordpress.stackexchange.com/questions/83999/g... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247730",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47359/"
] | How can I retrieve the current URL (whether homepage, archive, post type archive, category archive, etc) but always **without** the `/page/{pagenum}/` part if it's present? So, if the real URL is:
`example.com/category/uncategorized/`
OR
`example.com/category/uncategorized/page/2/`
then the return value will always be
`example.com/category/uncategorized/` | You can get the current URL through `home_url( $wp->request )`.
Try the example below:
```
global $wp;
// get current url with query string.
$current_url = home_url( $wp->request );
// get the position where '/page.. ' text start.
$pos = strpos($current_url , '/page');
// remove string from the specific postion
$finalurl = substr($current_url,0,$pos);
echo $finalurl;
``` |
247,751 | <p>I have found the following function to change the behavour of the Wordpress tag cloud:</p>
<pre><code>function widget_custom_tag_cloud($args) {
$args['orderby'] = 'count';
return $args;
}
add_filter( 'widget_tag_cloud_args', 'widget_custom_tag_cloud' );
</code></pre>
<p>However, I need to change the order from 'count' to 'menu_order'. Changing this line:</p>
<pre><code>$args['orderby'] = 'count';
</code></pre>
<p>to</p>
<pre><code>$args['orderby'] = 'menu_order';
</code></pre>
<p>does NOT work.</p>
<p>Is it possible to do this or do I need to write a custom widget from scratch?</p>
<p>Thanks in advance for any help!</p>
| [
{
"answer_id": 247752,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 3,
"selected": true,
"text": "<p>Tags (terms) do not have a <code>menu_order</code> (see the design of the table in the DB). </p>\n\n<p>If you wan... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84924/"
] | I have found the following function to change the behavour of the Wordpress tag cloud:
```
function widget_custom_tag_cloud($args) {
$args['orderby'] = 'count';
return $args;
}
add_filter( 'widget_tag_cloud_args', 'widget_custom_tag_cloud' );
```
However, I need to change the order from 'count' to 'menu\_order'. Changing this line:
```
$args['orderby'] = 'count';
```
to
```
$args['orderby'] = 'menu_order';
```
does NOT work.
Is it possible to do this or do I need to write a custom widget from scratch?
Thanks in advance for any help! | Tags (terms) do not have a `menu_order` (see the design of the table in the DB).
If you want to give terms a 'menu\_order' you will need to create this yourself.
As long as your WP is >= 4.4.0, you can make use of the feature `term_meta`.
This is to terms what post meta is to posts.
You can create a 'menu\_order' 'custom field' for terms and then you can set the menu order when creating/editing a term.
The relevant functions are:
```
add_term_meta();
update_term_meta();
get_term_meta();
delete_term_meta();
```
See here - <https://codex.wordpress.org/Function_Reference/add_term_meta>
And when query, your code won't do the trick for term meta. You need to write your own widget, that contains `get_terms()`. E.g.
```
$args = array(
'taxonomy' => 'taxonomy_name', //can be array with multiple tax
'meta_key' => 'menu_order',
'orderby' => 'meta_value',
'order' => 'DESC',
);
$terms = get_terms($args);
```
To build the UI in admin panel & saving functions for adding/editing term's meta, the proccess is a little long for a SO/SE answer, I think.
If you Google 'wp term meta' you'll find out how to do it.
You will need 4 or 5 functions in all.
The hooks you will use are:
```
{$taxonomy}_add_form_fields // add the custom field to the 'new term' form
{$taxonomy}_edit_form_fields // add the custom field to the 'edit term' form
create_{$taxonomy} // for saving the term meta from the 'new term' form
edit_{$taxonomy} // for saving the term meta from the 'edit term' form
manage_edit-{$taxonomy}_columns // OPTIONAL adds a column, for the custom field, in the terms table for the taxonomy
```
Or, use a plugin like [this one](https://wordpress.org/plugins/wp-custom-taxonomy-meta/) (or copy the code in it). |
247,766 | <p>I've installed Woocomerce plugin and custom post type 'product'. There are also categories of this type named 'product_cat'. I need to display name of categories on single-product.php</p>
<p>I've tried in this way:</p>
<pre><code><?php $term = get_term_by( 'name', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); echo $term->name; ?>
</code></pre>
<p>But it's unsucessful. When I checked the type that returned to <em>$term</em>, it displayed as boolean.</p>
| [
{
"answer_id": 247752,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 3,
"selected": true,
"text": "<p>Tags (terms) do not have a <code>menu_order</code> (see the design of the table in the DB). </p>\n\n<p>If you wan... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247766",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107941/"
] | I've installed Woocomerce plugin and custom post type 'product'. There are also categories of this type named 'product\_cat'. I need to display name of categories on single-product.php
I've tried in this way:
```
<?php $term = get_term_by( 'name', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); echo $term->name; ?>
```
But it's unsucessful. When I checked the type that returned to *$term*, it displayed as boolean. | Tags (terms) do not have a `menu_order` (see the design of the table in the DB).
If you want to give terms a 'menu\_order' you will need to create this yourself.
As long as your WP is >= 4.4.0, you can make use of the feature `term_meta`.
This is to terms what post meta is to posts.
You can create a 'menu\_order' 'custom field' for terms and then you can set the menu order when creating/editing a term.
The relevant functions are:
```
add_term_meta();
update_term_meta();
get_term_meta();
delete_term_meta();
```
See here - <https://codex.wordpress.org/Function_Reference/add_term_meta>
And when query, your code won't do the trick for term meta. You need to write your own widget, that contains `get_terms()`. E.g.
```
$args = array(
'taxonomy' => 'taxonomy_name', //can be array with multiple tax
'meta_key' => 'menu_order',
'orderby' => 'meta_value',
'order' => 'DESC',
);
$terms = get_terms($args);
```
To build the UI in admin panel & saving functions for adding/editing term's meta, the proccess is a little long for a SO/SE answer, I think.
If you Google 'wp term meta' you'll find out how to do it.
You will need 4 or 5 functions in all.
The hooks you will use are:
```
{$taxonomy}_add_form_fields // add the custom field to the 'new term' form
{$taxonomy}_edit_form_fields // add the custom field to the 'edit term' form
create_{$taxonomy} // for saving the term meta from the 'new term' form
edit_{$taxonomy} // for saving the term meta from the 'edit term' form
manage_edit-{$taxonomy}_columns // OPTIONAL adds a column, for the custom field, in the terms table for the taxonomy
```
Or, use a plugin like [this one](https://wordpress.org/plugins/wp-custom-taxonomy-meta/) (or copy the code in it). |
247,773 | <p>I'm looking to create and display a separate menu for a specific page. This menu needs to be in the primary location. So for example, on the Home page and the Contact page you would have: Home | About us | Contact. And on the "About us" page, you could show a different menu for example: Menu link 1 | Menu link 2 | Menu link 3. I have been trying for ours to do this with no luck. I literally have been looking at this for so long I don't even know where to start anymore. :( I'm hoping it's something like the code below.. Anyway, any help would be greatly appreciated. Thanks </p>
<pre><code>function my_example_menu() {
register_nav_menu('example-menu',__( 'Example Menu' ));
}
add_action( 'init', 'my_example_menu' );
wp_nav_menu( array(
'theme_location' => 'my-example-menu',
'container_class' => 'my-example-menu-class' ) );
function my_display_example_menu() {
if (is_page('about-us')) {
unregister_nav_menu( 'Primary Navigation' );
register_nav_menu( 'Example Menu' );
}
}
</code></pre>
<p>//EDIT</p>
<p>Parent theme nav</p>
<pre><code><?php truethemes_before_primary_navigation_hook();// action hook ?>
<nav role="navigation">
<?php if('true' == $ubermenu):
wp_nav_menu(array(
'theme_location' => 'Primary Navigation' ,
'depth' => 0 ,
'container' => false ,
'walker' => new description_walker() ));
else: ?>
<ul id="menu-main-nav" class="sf-menu">
<?php wp_nav_menu(array(
'theme_location' => 'Primary Navigation' ,
'depth' => 0 ,
'container' => false ,
'walker' => new description_walker() )); ?>
</ul>
<?php endif; //end uberMenu check ?>
</nav>
<?php truethemes_after_primary_navigation_hook();// action hook ?>
</code></pre>
| [
{
"answer_id": 247776,
"author": "Fabian Marz",
"author_id": 77421,
"author_profile": "https://wordpress.stackexchange.com/users/77421",
"pm_score": 2,
"selected": true,
"text": "<p>As you can read from the <a href=\"https://codex.wordpress.org/Function_Reference/register_nav_menu\" rel=... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247773",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98778/"
] | I'm looking to create and display a separate menu for a specific page. This menu needs to be in the primary location. So for example, on the Home page and the Contact page you would have: Home | About us | Contact. And on the "About us" page, you could show a different menu for example: Menu link 1 | Menu link 2 | Menu link 3. I have been trying for ours to do this with no luck. I literally have been looking at this for so long I don't even know where to start anymore. :( I'm hoping it's something like the code below.. Anyway, any help would be greatly appreciated. Thanks
```
function my_example_menu() {
register_nav_menu('example-menu',__( 'Example Menu' ));
}
add_action( 'init', 'my_example_menu' );
wp_nav_menu( array(
'theme_location' => 'my-example-menu',
'container_class' => 'my-example-menu-class' ) );
function my_display_example_menu() {
if (is_page('about-us')) {
unregister_nav_menu( 'Primary Navigation' );
register_nav_menu( 'Example Menu' );
}
}
```
//EDIT
Parent theme nav
```
<?php truethemes_before_primary_navigation_hook();// action hook ?>
<nav role="navigation">
<?php if('true' == $ubermenu):
wp_nav_menu(array(
'theme_location' => 'Primary Navigation' ,
'depth' => 0 ,
'container' => false ,
'walker' => new description_walker() ));
else: ?>
<ul id="menu-main-nav" class="sf-menu">
<?php wp_nav_menu(array(
'theme_location' => 'Primary Navigation' ,
'depth' => 0 ,
'container' => false ,
'walker' => new description_walker() )); ?>
</ul>
<?php endif; //end uberMenu check ?>
</nav>
<?php truethemes_after_primary_navigation_hook();// action hook ?>
``` | As you can read from the [documentation](https://codex.wordpress.org/Function_Reference/register_nav_menu) `register_nav_menu` is used to register a menu in the menu editor. Your code will affect the backend only. Also you should pass a slug like string as the first parameter. If you want to change the display of the menu, you could simple write a condition which will change the parameters of [wp\_nav\_menu](https://developer.wordpress.org/reference/functions/wp_nav_menu/). Like the following:
```php
// header.php (or similar)
wp_nav_menu([
'menu' => (is_page('about-us') ? 'primary-navigation' ? 'example-menu'),
]);
```
Otherwise you could also register a menu and change the value of the `theme_location` parameter to make the menu configurable by the user.
### Update:
To achieve this via a filter hook
```php
// functions.php
add_filter('wp_nav_menu_args', function ($args) {
if (is_page('about-us')) {
$args['menu'] = 'my-custom-menu';
}
return $args;
});
``` |
247,782 | <p>Is there a way (and if so, 'how?') to apply a conditional to a page/post for which the slug contains a specific word.</p>
<p>In the case of the Codex example of:</p>
<pre><code>is_single( 'beef-stew' )
</code></pre>
<p>The condition will still apply if the slug contains 'beef', rather than being 'beef-stew'.</p>
<p>UPDATE: In response to a request for context...</p>
<p>I have a nav-menu which uses a conditional statement (example below) to apply a css class to an item when it's the page being viewed.</p>
<pre><code> <?php if (is_single('mon')) { echo " class=\"current\""; }?>
</code></pre>
<p>In the example above 'mon' is 'monday', with similar for other days in a weekly schedule. By adding to a template, it can be used for any day provided I set an appropriate slug... an example of which is to use 'mon' instead of 'Monday April 4'.</p>
<p>I want to apply the condition to just part of the slug, thus saving the time of manually modifying the slug prior to saving... and also removing the situation of mis-function if I forget to do so.</p>
| [
{
"answer_id": 247783,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress has no conditional for substring testing but you can do this using PHPs built-in function: <a hre... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247782",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103213/"
] | Is there a way (and if so, 'how?') to apply a conditional to a page/post for which the slug contains a specific word.
In the case of the Codex example of:
```
is_single( 'beef-stew' )
```
The condition will still apply if the slug contains 'beef', rather than being 'beef-stew'.
UPDATE: In response to a request for context...
I have a nav-menu which uses a conditional statement (example below) to apply a css class to an item when it's the page being viewed.
```
<?php if (is_single('mon')) { echo " class=\"current\""; }?>
```
In the example above 'mon' is 'monday', with similar for other days in a weekly schedule. By adding to a template, it can be used for any day provided I set an appropriate slug... an example of which is to use 'mon' instead of 'Monday April 4'.
I want to apply the condition to just part of the slug, thus saving the time of manually modifying the slug prior to saving... and also removing the situation of mis-function if I forget to do so. | WordPress has no conditional for substring testing but you can do this using PHPs built-in function: [`strpos()`](http://php.net/manual/en/function.strpos.php)
```
global $post;
if( false !== strpos( $post->post_name, 'beef' ) ) {
// Do Things
}
```
The above returns true if `beef` is found somewhere in the post slug. |
247,790 | <p>Is there a possible way to get the alt text from the media file by just knowing the URL? For example, if the path to my image is <code>/bc/wp-content/uploads/placeholder-image.png</code> is there a way (just by using that URL) to get the alt text of that image. I know you usually need the ID and such, trying to find a way around this.</p>
<p>PHP</p>
<pre><code><img src="/bc/wp-content/uploads/placeholder-image.png" alt="<?php /* do something */ ?>" />
</code></pre>
| [
{
"answer_id": 247792,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 3,
"selected": false,
"text": "<p>Using the function found <a href=\"https://pippinsplugins.com/retrieve-attachment-id-from-image-url/\" rel=\"... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247790",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93770/"
] | Is there a possible way to get the alt text from the media file by just knowing the URL? For example, if the path to my image is `/bc/wp-content/uploads/placeholder-image.png` is there a way (just by using that URL) to get the alt text of that image. I know you usually need the ID and such, trying to find a way around this.
PHP
```
<img src="/bc/wp-content/uploads/placeholder-image.png" alt="<?php /* do something */ ?>" />
``` | Using the function found [here](https://pippinsplugins.com/retrieve-attachment-id-from-image-url/), you could add this to your functions.php
```
// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
```
But to use it, you need the full image URL.
```
$img_url = get_bloginfo('url') . '/bc/wp-content/uploads/placeholder-image.png';
if ( $img_id = pippin_get_image_id($img_url) ) {
// Using wp_get_attachment_image should return your alt text added in the WordPress admin.
echo wp_get_attachment_image( $img_id, 'full' );
} else {
// Fallback in case it's not found.
echo '<img src="' . $img_url . '" alt="" />';
}
``` |
247,800 | <p>I know this has been discussed in a couple of other posts but none of them seem to have the correct answer/solution to the question. I tried using all the suggested functions mentioned in the other posts but none seem to work. When a wrong password is introduced nothing happens(just the standard redirect to the same page)
The only one getting close to the answer is the following code provided by <a href="https://wordpress.stackexchange.com/users/73/toscho">toscho</a> on this thread - <a href="https://wordpress.stackexchange.com/questions/71284/add-error-message-on-password-protected-page?rq=1">Add error message on password protected page</a> but unfortunately the error message shows regardless if the password was not introduced yet or as soon as you land on the page:</p>
<pre><code><?php
add_filter( 'the_password_form', 'wpse_71284_custom_post_password_msg' );
function wpse_71284_custom_post_password_msg( $form )
{
// No cookie, the user has not sent anything until now.
if ( ! isset ( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) )
return $form;
// Translate and escape.
$msg = esc_html__( 'Sorry, your password is wrong.', 'your_text_domain' );
// We have a cookie, but it doesn’t match the password.
$msg = "<p class='custom-password-message'>$msg</p>";
return $msg . $form;
}
?>
</code></pre>
<p>Your time and input is much appreciated.</p>
| [
{
"answer_id": 247942,
"author": "Michelle",
"author_id": 16,
"author_profile": "https://wordpress.stackexchange.com/users/16",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>add_filter( 'the_password_form', 'wpse_71284_custom_post_password_msg' );\n\n/**\n * A... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247800",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107950/"
] | I know this has been discussed in a couple of other posts but none of them seem to have the correct answer/solution to the question. I tried using all the suggested functions mentioned in the other posts but none seem to work. When a wrong password is introduced nothing happens(just the standard redirect to the same page)
The only one getting close to the answer is the following code provided by [toscho](https://wordpress.stackexchange.com/users/73/toscho) on this thread - [Add error message on password protected page](https://wordpress.stackexchange.com/questions/71284/add-error-message-on-password-protected-page?rq=1) but unfortunately the error message shows regardless if the password was not introduced yet or as soon as you land on the page:
```
<?php
add_filter( 'the_password_form', 'wpse_71284_custom_post_password_msg' );
function wpse_71284_custom_post_password_msg( $form )
{
// No cookie, the user has not sent anything until now.
if ( ! isset ( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) )
return $form;
// Translate and escape.
$msg = esc_html__( 'Sorry, your password is wrong.', 'your_text_domain' );
// We have a cookie, but it doesn’t match the password.
$msg = "<p class='custom-password-message'>$msg</p>";
return $msg . $form;
}
?>
```
Your time and input is much appreciated. | Try this:
```
add_filter( 'the_password_form', 'wpse_71284_custom_post_password_msg' );
/**
* Add a message to the password form.
*
* @wp-hook the_password_form
* @param string $form
* @return string
*/
function wpse_71284_custom_post_password_msg( $form )
{
// No cookie, the user has not sent anything until now.
if ( ! isset ( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) )
return $form;
// No cookie, person just submitted the form on this page and got the password wrong
if (wp_get_referer() == get_permalink()) {
// Translate and escape.
$msg = esc_html__( 'Sorry, your password is wrong.', 'your_text_domain' );
// We have a cookie, but it doesn’t match the password.
$msg = "<p class='custom-password-message'>$msg</p>";
} else {
$msg = "";
}
return $msg . $form;
}
``` |
247,806 | <p>I have a page that I designated as my front page using the <code>reading</code> portion of settings in the dashboard. When I place a script inside of an if statement using <code>is_front_page</code> in functions.php, it only runs on that designated front-page, and not the others (indicating the page has been designated correctly). </p>
<p>However, I have an <code>if</code> statement in my header.php file that also uses <code>is_front_page</code>, and that seems to be triggering on all my pages (including the ones that I have not designated as the front page).</p>
<p>What is going on? Can you not run <code>is_front_page</code> from within header.php and have that code only apply to the front-page header? Am I missing something?</p>
<p>This is the code that I have placed in my header.php file that is returning true on all pages </p>
<p><code><?php echo ( is_front_page ) ? 'frontPageLogo' : NULL; ?></code></p>
<p>(I believe it is returning true on all pages because it always echoes 'frontPageLogo')</p>
| [
{
"answer_id": 247811,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 4,
"selected": true,
"text": "<p>Yes it should work in the header file just like normal. Try using a standard IF statement instead of shorthand... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247806",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
] | I have a page that I designated as my front page using the `reading` portion of settings in the dashboard. When I place a script inside of an if statement using `is_front_page` in functions.php, it only runs on that designated front-page, and not the others (indicating the page has been designated correctly).
However, I have an `if` statement in my header.php file that also uses `is_front_page`, and that seems to be triggering on all my pages (including the ones that I have not designated as the front page).
What is going on? Can you not run `is_front_page` from within header.php and have that code only apply to the front-page header? Am I missing something?
This is the code that I have placed in my header.php file that is returning true on all pages
`<?php echo ( is_front_page ) ? 'frontPageLogo' : NULL; ?>`
(I believe it is returning true on all pages because it always echoes 'frontPageLogo') | Yes it should work in the header file just like normal. Try using a standard IF statement instead of shorthand:
```
if( is_front_page() ){
echo 'Front page!';
}
```
You must have it configured in the settings to use:
`A static page (select below)` instead of `Your latest posts`
If you want `is_front_page()` to only return TRUE when viewing the page you select from the dropdown for **Front Page** (which it sounds like you do)
You can then use `is_home()` if a static page is set for the front page of the site, this function will return true only on the page you set as the “Posts page”.
<https://developer.wordpress.org/reference/functions/is_home/>
Whether [is\_home()](https://developer.wordpress.org/reference/functions/is_home/) or [is\_front\_page()](https://developer.wordpress.org/reference/functions/is_front_page/) return `true` or `false` depends on the values of certain option values:
* `get_option( 'show_on_front' )`: returns either `'posts'` or `'page'`
* `get_option( 'page_on_front' )`: returns the `ID` of the static page assigned to the front page
* `get_option( 'page_for_posts' )`: returns the `ID` of the static page assigned to the blog posts index (posts page)
When using these query conditionals:
* If `'posts' == get_option( 'show_on_front' )`:
+ On the site front page:
- `is_front_page()` will return `true`
- `is_home()` will return `true`
+ If assigned, WordPress ignores the pages assigned to display the site front page or the blog posts index
* If `'page' == get_option( 'show_on_front' )`:
+ On the page assigned to display the site front page:
- `is_front_page()` will return `true`
- `is_home()` will return `false`
+ On the page assigned to display the blog posts index:
- `is_front_page()` will return `false`
- `is_home()` will return `true` |
247,808 | <p>I have an expiry date ACF field <code>'post_end_date'</code> which has been applied to multiple post types, including <code>'post'</code>.</p>
<p>I'm trying to filter out any posts, across the entire site, where today's date is greater than the value <code>'post_end_date'</code>; in other words the post has expired. I've checked that <code>'post_end_date'</code> value returns a number in the same format as <code>date('Ymd')</code>. e.g. </p>
<pre><code>echo date('Ymd'); // returns 20161128 for today
echo get_field('post_end_date'); // returns 20161127 for yesterday
</code></pre>
<p>I figured the best way would be to just do a numerical comparison between today's date and <code>'post_end_date'</code> value.</p>
<p>This is my code:</p>
<pre><code> function expiry_filter($query) {
if( !is_admin() && $query->is_main_query() ) :
$today = $expire = date('Ymd');
if ( get_field('post_end_date') ) :
$expire = get_field('post_end_date');
endif;
$query->set( 'meta_query', array(
array(
'key' => $expire,
'value' => $today,
'compare' => '<',
'type' => 'NUMERIC'
)
));
endif;
}
add_action( 'pre_get_posts', 'expiry_filter' );
</code></pre>
<p>At this point, I was just trying to get it to work for the <code>'post'</code> post type. I have checked that I haven't used the wrong 'compare' operator. I've tried with and without the <code>$query->is_main_query()</code> conditional.</p>
<p>The result I'm getting with the code above is ALL posts are being filtered out.</p>
<p>Can someone suggest what I might be doing wrong here?</p>
<p>Thanks in advance. </p>
| [
{
"answer_id": 247811,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 4,
"selected": true,
"text": "<p>Yes it should work in the header file just like normal. Try using a standard IF statement instead of shorthand... | 2016/11/29 | [
"https://wordpress.stackexchange.com/questions/247808",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47170/"
] | I have an expiry date ACF field `'post_end_date'` which has been applied to multiple post types, including `'post'`.
I'm trying to filter out any posts, across the entire site, where today's date is greater than the value `'post_end_date'`; in other words the post has expired. I've checked that `'post_end_date'` value returns a number in the same format as `date('Ymd')`. e.g.
```
echo date('Ymd'); // returns 20161128 for today
echo get_field('post_end_date'); // returns 20161127 for yesterday
```
I figured the best way would be to just do a numerical comparison between today's date and `'post_end_date'` value.
This is my code:
```
function expiry_filter($query) {
if( !is_admin() && $query->is_main_query() ) :
$today = $expire = date('Ymd');
if ( get_field('post_end_date') ) :
$expire = get_field('post_end_date');
endif;
$query->set( 'meta_query', array(
array(
'key' => $expire,
'value' => $today,
'compare' => '<',
'type' => 'NUMERIC'
)
));
endif;
}
add_action( 'pre_get_posts', 'expiry_filter' );
```
At this point, I was just trying to get it to work for the `'post'` post type. I have checked that I haven't used the wrong 'compare' operator. I've tried with and without the `$query->is_main_query()` conditional.
The result I'm getting with the code above is ALL posts are being filtered out.
Can someone suggest what I might be doing wrong here?
Thanks in advance. | Yes it should work in the header file just like normal. Try using a standard IF statement instead of shorthand:
```
if( is_front_page() ){
echo 'Front page!';
}
```
You must have it configured in the settings to use:
`A static page (select below)` instead of `Your latest posts`
If you want `is_front_page()` to only return TRUE when viewing the page you select from the dropdown for **Front Page** (which it sounds like you do)
You can then use `is_home()` if a static page is set for the front page of the site, this function will return true only on the page you set as the “Posts page”.
<https://developer.wordpress.org/reference/functions/is_home/>
Whether [is\_home()](https://developer.wordpress.org/reference/functions/is_home/) or [is\_front\_page()](https://developer.wordpress.org/reference/functions/is_front_page/) return `true` or `false` depends on the values of certain option values:
* `get_option( 'show_on_front' )`: returns either `'posts'` or `'page'`
* `get_option( 'page_on_front' )`: returns the `ID` of the static page assigned to the front page
* `get_option( 'page_for_posts' )`: returns the `ID` of the static page assigned to the blog posts index (posts page)
When using these query conditionals:
* If `'posts' == get_option( 'show_on_front' )`:
+ On the site front page:
- `is_front_page()` will return `true`
- `is_home()` will return `true`
+ If assigned, WordPress ignores the pages assigned to display the site front page or the blog posts index
* If `'page' == get_option( 'show_on_front' )`:
+ On the page assigned to display the site front page:
- `is_front_page()` will return `true`
- `is_home()` will return `false`
+ On the page assigned to display the blog posts index:
- `is_front_page()` will return `false`
- `is_home()` will return `true` |
247,858 | <p>I am creating a menu for a documentation site very much like this: <a href="http://getbootstrap.com/components/" rel="nofollow noreferrer">http://getbootstrap.com/components/</a></p>
<p>I am using a hierarchical custom post type (manual).
I am currently using wp_list_pages() to output the list. This gives me the nested structure that I am looking for:</p>
<pre><code><ul>
<li>Parent Post</li>
<ul>
<li>Child Post</li>
<li>Child Post</li>
</ul>
<li>Parent Post</li>
<ul>
<li>Child Post</li>
<li>Child Post</li>
</ul>
</ul>
<!-- and so on -->
</code></pre>
<p>Unfortunately, wp_list_pages() outputs the permalink to the post like this:</p>
<pre><code><li class="page_item page-item-332"><a href="http://myurl.com/manual/introduction-to-the-manual/organization/">1.1 &#8211; Manual Organization</a></li>
</code></pre>
<p>and I need it to output the post_id like this:</p>
<pre><code><li class="page_item page-item-332"><a href="#332">1.1 &#8211; Manual Organization</a></li>
</code></pre>
<p>Also, here is my wp_list_pages code:</p>
<pre><code> <ul id="markdown-toc">
<li><h3><a href="#contents">Contents</a></h3></li>
<ul id="my_cutom_type-list">
<?php wp_list_pages( 'post_type=manual&title_li=' ); ?>
</ul>
</ul>
</code></pre>
| [
{
"answer_id": 247864,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 0,
"selected": false,
"text": "<p>You can done this by creating you custom Walker class and pass it's instance as argument while calling <code>wp_l... | 2016/11/30 | [
"https://wordpress.stackexchange.com/questions/247858",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99008/"
] | I am creating a menu for a documentation site very much like this: <http://getbootstrap.com/components/>
I am using a hierarchical custom post type (manual).
I am currently using wp\_list\_pages() to output the list. This gives me the nested structure that I am looking for:
```
<ul>
<li>Parent Post</li>
<ul>
<li>Child Post</li>
<li>Child Post</li>
</ul>
<li>Parent Post</li>
<ul>
<li>Child Post</li>
<li>Child Post</li>
</ul>
</ul>
<!-- and so on -->
```
Unfortunately, wp\_list\_pages() outputs the permalink to the post like this:
```
<li class="page_item page-item-332"><a href="http://myurl.com/manual/introduction-to-the-manual/organization/">1.1 – Manual Organization</a></li>
```
and I need it to output the post\_id like this:
```
<li class="page_item page-item-332"><a href="#332">1.1 – Manual Organization</a></li>
```
Also, here is my wp\_list\_pages code:
```
<ul id="markdown-toc">
<li><h3><a href="#contents">Contents</a></h3></li>
<ul id="my_cutom_type-list">
<?php wp_list_pages( 'post_type=manual&title_li=' ); ?>
</ul>
</ul>
``` | You could add a filter on `post_type_link`, which allows modification of custom post type permalinks before they are output.
The filter passes the custom post object as the 2nd argument, so we can use that to get the ID and form the new permalink:
```
function wpd_list_pages_permalink_filter( $permalink, $page ){
return '#' . $page->ID;
}
```
Then you can add and remove the filter when using `wp_list_pages`:
```
add_filter( 'post_type_link', 'wpd_list_pages_permalink_filter', 10, 2 );
wp_list_pages();
remove_filter( 'post_type_link', 'wpd_list_pages_permalink_filter', 10, 2 );
```
If your menu contained the built in `page` post type, you would use the `page_link` filter. Note in that case the 2nd argument is only the page's ID, not the full page object like in the `post_type_link` filter. |
247,859 | <p>I need to get the category id of the current post outside the loop. First I get the category based on the post id:</p>
<pre><code>global $wp_query;
$postcat = get_the_category( $wp_query->post->ID );
</code></pre>
<p>Now how to get the category id? I tried: <code>$cat_id = $postcat->term_id;</code> but it's not working.</p>
| [
{
"answer_id": 247860,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 4,
"selected": false,
"text": "<p>When you use <code>get_the_category()</code> function to get category's data, it return the array of object so yo... | 2016/11/30 | [
"https://wordpress.stackexchange.com/questions/247859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
] | I need to get the category id of the current post outside the loop. First I get the category based on the post id:
```
global $wp_query;
$postcat = get_the_category( $wp_query->post->ID );
```
Now how to get the category id? I tried: `$cat_id = $postcat->term_id;` but it's not working. | ```
function catName($cat_id) {
$cat_id = (int) $cat_id;
$category = &get_category($cat_id);
return $category->name;
}
function catLink($cat_id) {
$category = get_the_category();
$category_link = get_category_link($cat_id);
echo $category_link;
}
function catCustom() {
$cats = get_the_category($post->ID);
$parent = get_category($cats[1]->category_parent);
if (is_wp_error($parent)){
$cat = get_category($cats[0]);
}
else{
$cat = $parent;
}
echo '<a href="'.get_category_link($cat).'">'.$cat->name.'</a>';
}
```
USE `<a href="<?php catLink(1); ?>"> <?php catName(1); ?>` |
247,862 | <p>The WP REST API exposes a lot of information so I filter endpoints that aren't needed to expose. </p>
<p>I can't filter everything: The location of needed media files are exposed for example.</p>
<p>As an extra protection I'd like to mystify the default uri.</p>
<p>I would like to change for example: <code>http://example.com/wp-json/wp/v2/</code> to <code>http://example.com/mistified/wp/v2/</code></p>
<p>Is this rather easy possible?</p>
| [
{
"answer_id": 247882,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the <code>json_url_prefix</code> hook to remove <code>'wp-json'</code> across all API routes. The ... | 2016/11/30 | [
"https://wordpress.stackexchange.com/questions/247862",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44262/"
] | The WP REST API exposes a lot of information so I filter endpoints that aren't needed to expose.
I can't filter everything: The location of needed media files are exposed for example.
As an extra protection I'd like to mystify the default uri.
I would like to change for example: `http://example.com/wp-json/wp/v2/` to `http://example.com/mistified/wp/v2/`
Is this rather easy possible? | Please note that for current versions of WordPress, using the `json_url_prefix` filter no longer works.
On WordPress 4.7 (and using the REST API from the core instead of a plugin), this is what I needed to change the API prefix.
```
add_filter( 'rest_url_prefix', 'my_theme_api_slug');
function my_theme_api_slug( $slug ) { return 'api'; }
```
If this doesn't work straight away, you'll need to flush the rewrite rules. You can run this piece of code once to do so (don't leave it in your code so it runs everytime):
```
flush_rewrite_rules(true);
``` |
247,888 | <p>I have created a custom post type for "Solutions" which will eventually replace all products that have been added in Woocommerce as I no longer have the need for a shopping cart.</p>
<p>So I need to copy the data from each product to a new 'solution' CPT. </p>
<p>I have the below code to set up the new post type:</p>
<pre><code>function create_solution_post_type()
{
register_post_type('solution',
[
'labels' => [
'name' => __('Solutions'),
'singular_name' => __('Solution'),
],
'public' => true,
'has_archive' => true,
'rewrite' => [
'slug' => 'product',
],
]
);
register_taxonomy(
'solution-area',
'solution',
[
'labels' => [
'name' => __( 'Solution Areas' ),
'singular_name' => __( 'Solution Area' ),
],
'hierarchical' => true,
'show_admin_column' => true,
]
);
}
add_action('init', 'create_solution_post_type');
</code></pre>
<p>After resetting the permalinks, it works fine for the custom post type but whenever I go to view a woocommerce product page I get, "Oops! That page can’t be found." </p>
<p>I assume its because the slug for the product and solution is the same? Although I don't really understand why this would be a problem if the overall url is different eg. example.com/product/product-name in woocommommerce will become example.com/product/product-name-2 for the custom post type until I delete the products and remove woocommerce.</p>
<p>I need the CTP 'solution' and woocommerce products working in conjunction with the same 'products' slug. How can I achieve this?</p>
<p>Many thanks in advance for your help.</p>
| [
{
"answer_id": 248142,
"author": "Vitaliy Kukin",
"author_id": 34421,
"author_profile": "https://wordpress.stackexchange.com/users/34421",
"pm_score": 0,
"selected": false,
"text": "<p>You are replaced only slug but not a post type. To move all post type product to solution you should go... | 2016/11/30 | [
"https://wordpress.stackexchange.com/questions/247888",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70019/"
] | I have created a custom post type for "Solutions" which will eventually replace all products that have been added in Woocommerce as I no longer have the need for a shopping cart.
So I need to copy the data from each product to a new 'solution' CPT.
I have the below code to set up the new post type:
```
function create_solution_post_type()
{
register_post_type('solution',
[
'labels' => [
'name' => __('Solutions'),
'singular_name' => __('Solution'),
],
'public' => true,
'has_archive' => true,
'rewrite' => [
'slug' => 'product',
],
]
);
register_taxonomy(
'solution-area',
'solution',
[
'labels' => [
'name' => __( 'Solution Areas' ),
'singular_name' => __( 'Solution Area' ),
],
'hierarchical' => true,
'show_admin_column' => true,
]
);
}
add_action('init', 'create_solution_post_type');
```
After resetting the permalinks, it works fine for the custom post type but whenever I go to view a woocommerce product page I get, "Oops! That page can’t be found."
I assume its because the slug for the product and solution is the same? Although I don't really understand why this would be a problem if the overall url is different eg. example.com/product/product-name in woocommommerce will become example.com/product/product-name-2 for the custom post type until I delete the products and remove woocommerce.
I need the CTP 'solution' and woocommerce products working in conjunction with the same 'products' slug. How can I achieve this?
Many thanks in advance for your help. | Looks like slugs have to be unique for all posts according to wordpress documentation.
>
> Post slugs must be unique across all posts
>
>
>
Therefore it is not possible to have the same slug for woocommcerce products and the CPT as I assume Woocommcerce Products are just posts. I will have to have a different slug and use redirects.
Thanks for your help guys. |
247,895 | <p>I'm using the following code to filter posts on category pages so only sticky posts are displayed.</p>
<pre><code>add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
$sticky_posts = get_option( 'sticky_posts' );
if( ! empty( $sticky_posts ) )
$q->set( 'post__in', (array) $sticky_posts );
}
} );
?>
</code></pre>
<p>The problem is, if there are no sticky posts then all the category's posts are displayed. If there are no sticky posts I don't want any posts to be displayed.</p>
| [
{
"answer_id": 247898,
"author": "Ellimist",
"author_id": 28296,
"author_profile": "https://wordpress.stackexchange.com/users/28296",
"pm_score": 3,
"selected": true,
"text": "<p>Just set 'post__in' to a null array.</p>\n\n<pre><code>add_action( 'pre_get_posts', function( \\WP_Query $q )... | 2016/11/30 | [
"https://wordpress.stackexchange.com/questions/247895",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
] | I'm using the following code to filter posts on category pages so only sticky posts are displayed.
```
add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
$sticky_posts = get_option( 'sticky_posts' );
if( ! empty( $sticky_posts ) )
$q->set( 'post__in', (array) $sticky_posts );
}
} );
?>
```
The problem is, if there are no sticky posts then all the category's posts are displayed. If there are no sticky posts I don't want any posts to be displayed. | Just set 'post\_\_in' to a null array.
```
add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
$sticky_posts = get_option( 'sticky_posts' );
//If there are sticky posts
if( ! empty( $sticky_posts ) ) {
$q->set( 'post__in', (array) $sticky_posts );
}
//If not
else {
$q->set( 'post__in', array(0) );
}
}
} );
``` |
247,899 | <p>I have multiple Wordpress installations on MAMP, which all have their own file structure (wp-admin, wp-includes etc.).</p>
<p>Because they are all development sites, it doesn't make sense to include the whole wordpress installation for every site.</p>
<p>Is it possible to only have one instance of Wordpress, and somehow link the correct wp-config.php and wp-content folder to each site, to reduce disk space?</p>
| [
{
"answer_id": 247898,
"author": "Ellimist",
"author_id": 28296,
"author_profile": "https://wordpress.stackexchange.com/users/28296",
"pm_score": 3,
"selected": true,
"text": "<p>Just set 'post__in' to a null array.</p>\n\n<pre><code>add_action( 'pre_get_posts', function( \\WP_Query $q )... | 2016/11/30 | [
"https://wordpress.stackexchange.com/questions/247899",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48745/"
] | I have multiple Wordpress installations on MAMP, which all have their own file structure (wp-admin, wp-includes etc.).
Because they are all development sites, it doesn't make sense to include the whole wordpress installation for every site.
Is it possible to only have one instance of Wordpress, and somehow link the correct wp-config.php and wp-content folder to each site, to reduce disk space? | Just set 'post\_\_in' to a null array.
```
add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
$sticky_posts = get_option( 'sticky_posts' );
//If there are sticky posts
if( ! empty( $sticky_posts ) ) {
$q->set( 'post__in', (array) $sticky_posts );
}
//If not
else {
$q->set( 'post__in', array(0) );
}
}
} );
``` |
247,948 | <p>I am trying to get from this kind of url:</p>
<pre><code>domain.com/page/classes/?language=english&need=pro
</code></pre>
<p>To this:</p>
<pre><code>domain.com/class/english-pro
</code></pre>
<hr>
<p><strong>MORE INFORMATIONS</strong></p>
<p>Both variables have been added as <code>query_vars</code>. <code>classes</code> is the current page and <code>page</code> is the parent page.</p>
<hr>
<p><strong>WHAT I'VE TRIED</strong></p>
<p>Here is the rewrite rule I've tried but it's not working.</p>
<pre><code>function custom_rewrite() {
add_rewrite_rule( 'class/([^/]+)-([^/]+)$', 'index.php?language=$matches[1]&need=$matches[2]', 'top' );
}
add_action( 'init', 'custom_rewrite' );
</code></pre>
<p>For some reasons I can't get my head around the regex expressions... Thanks for your help!</p>
<hr>
<p><strong>UPDATE 1</strong></p>
<p>With a bit of searching this what I came up with:</p>
<pre><code>function custom_rewrite() {
add_rewrite_tag( '%_language%', '([a-zA-Z\d\-_+]+)' );
add_rewrite_tag( '%_need%', '([a-zA-Z\d\-_+]+)' );
add_rewrite_rule( 'class/([a-zA-Z\d\-_+]+)-([a-zA-Z\d\-_+]+)?', 'index.php?_language=$matches[1]&_need=$matches[2]', 'top' );
}
add_action( 'init', 'custom_rewrite' );
</code></pre>
<p>But it's still not working.</p>
<hr>
<p><strong>UPDATE 2</strong></p>
<p>I've made some changes so that it gets easier to do the redirect. Here is how it works:</p>
<ul>
<li>I've got two selects in a form whith which people can choose a <code>language</code> and a <code>need</code>. Both are declared query variables.</li>
<li>When the form validates it loads this url: <code>domain.com/page/classes/?_language=english&_need=pro</code>.</li>
<li>The result's page loads informations from a custom post type named with the following structure <strong><em>language</em>-<em>need</em></strong>. I get the informations by using a <code>query_posts</code> that build the <code>name</code> from the <code>query variables</code>.</li>
</ul>
<p>Now what I want is simple : to redirect the defaut url (<code>domain.com/page/classes/?language=english&need=pro</code>) to this new url (<code>domain.com/class/english-pro</code>) while still loading the same informations**.</p>
<hr>
<p><strong>UPDATE 3</strong></p>
<p>I've tried @jgraup solution below (without the <code>prefix__pre_post_link</code> function as I've simplified my url to not need it) but it's not working (my custom post type is using the same settings</p>
<pre><code>if ( ! class_exists( 'PrefixClassesRewrites' ) ) {
class PrefixClassesRewrites {
const POST_TYPE_SLUG = 'lang';
function __invoke() {
add_action( 'init', array ( $this, 'prefix__init' ) );
add_action( 'pre_get_posts', array ( $this, 'prefix__pre_get_posts' ) );
}
public function prefix__init() {
// custom query params that we check for later
add_rewrite_tag( '%_language%', '([a-zA-Z\d\-_+]+)' );
add_rewrite_tag( '%_need%', '([a-zA-Z\d\-_+]+)' );
add_rewrite_tag( '%_page_class%', '_page_class' );
// rewrite rule to transform the URL into params
add_rewrite_rule( 'class/([a-zA-Z\d\-_+]+)-([a-zA-Z\d\-_+]+)?', 'index.php?_language=$matches[1]&_need=$matches[2]&_page_class=1', 'top' );
flush_rewrite_rules(); // <-- for testing only | removed once the rewrite rules are in place
}
public function prefix__pre_get_posts( $query ) {
if ( isset( $query->query_vars[ '_page_class' ] ) ) {
// Convert the variables to a custom post type name.
$name = implode( '-', array (
$query->query_vars[ '_langue' ],
$query->query_vars[ '_besoin' ],
) );
// Add the name and post_type to the query.
$query->query_vars[ 'name' ] = $name;
$query->query_vars[ 'post_type' ] = array ( static::POST_TYPE_SLUG );
// Nothing else to do here.
return;
}
}
}
$prefixClassesRewrites = new PrefixClassesRewrites();
$prefixClassesRewrites(); // kick off the process
}
</code></pre>
<p>The thing is that nothing has changed, my url is not being rewritten. By the way, is the rewriting tule supposed to be in y htaccess when it's working?</p>
| [
{
"answer_id": 248322,
"author": "Varun Kumar",
"author_id": 103095,
"author_profile": "https://wordpress.stackexchange.com/users/103095",
"pm_score": 1,
"selected": false,
"text": "<p>Hope this will work out for as it did for me.</p>\n\n<pre><code>add_filter('rewrite_rules_array', 'inse... | 2016/11/30 | [
"https://wordpress.stackexchange.com/questions/247948",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54879/"
] | I am trying to get from this kind of url:
```
domain.com/page/classes/?language=english&need=pro
```
To this:
```
domain.com/class/english-pro
```
---
**MORE INFORMATIONS**
Both variables have been added as `query_vars`. `classes` is the current page and `page` is the parent page.
---
**WHAT I'VE TRIED**
Here is the rewrite rule I've tried but it's not working.
```
function custom_rewrite() {
add_rewrite_rule( 'class/([^/]+)-([^/]+)$', 'index.php?language=$matches[1]&need=$matches[2]', 'top' );
}
add_action( 'init', 'custom_rewrite' );
```
For some reasons I can't get my head around the regex expressions... Thanks for your help!
---
**UPDATE 1**
With a bit of searching this what I came up with:
```
function custom_rewrite() {
add_rewrite_tag( '%_language%', '([a-zA-Z\d\-_+]+)' );
add_rewrite_tag( '%_need%', '([a-zA-Z\d\-_+]+)' );
add_rewrite_rule( 'class/([a-zA-Z\d\-_+]+)-([a-zA-Z\d\-_+]+)?', 'index.php?_language=$matches[1]&_need=$matches[2]', 'top' );
}
add_action( 'init', 'custom_rewrite' );
```
But it's still not working.
---
**UPDATE 2**
I've made some changes so that it gets easier to do the redirect. Here is how it works:
* I've got two selects in a form whith which people can choose a `language` and a `need`. Both are declared query variables.
* When the form validates it loads this url: `domain.com/page/classes/?_language=english&_need=pro`.
* The result's page loads informations from a custom post type named with the following structure ***language*-*need***. I get the informations by using a `query_posts` that build the `name` from the `query variables`.
Now what I want is simple : to redirect the defaut url (`domain.com/page/classes/?language=english&need=pro`) to this new url (`domain.com/class/english-pro`) while still loading the same informations\*\*.
---
**UPDATE 3**
I've tried @jgraup solution below (without the `prefix__pre_post_link` function as I've simplified my url to not need it) but it's not working (my custom post type is using the same settings
```
if ( ! class_exists( 'PrefixClassesRewrites' ) ) {
class PrefixClassesRewrites {
const POST_TYPE_SLUG = 'lang';
function __invoke() {
add_action( 'init', array ( $this, 'prefix__init' ) );
add_action( 'pre_get_posts', array ( $this, 'prefix__pre_get_posts' ) );
}
public function prefix__init() {
// custom query params that we check for later
add_rewrite_tag( '%_language%', '([a-zA-Z\d\-_+]+)' );
add_rewrite_tag( '%_need%', '([a-zA-Z\d\-_+]+)' );
add_rewrite_tag( '%_page_class%', '_page_class' );
// rewrite rule to transform the URL into params
add_rewrite_rule( 'class/([a-zA-Z\d\-_+]+)-([a-zA-Z\d\-_+]+)?', 'index.php?_language=$matches[1]&_need=$matches[2]&_page_class=1', 'top' );
flush_rewrite_rules(); // <-- for testing only | removed once the rewrite rules are in place
}
public function prefix__pre_get_posts( $query ) {
if ( isset( $query->query_vars[ '_page_class' ] ) ) {
// Convert the variables to a custom post type name.
$name = implode( '-', array (
$query->query_vars[ '_langue' ],
$query->query_vars[ '_besoin' ],
) );
// Add the name and post_type to the query.
$query->query_vars[ 'name' ] = $name;
$query->query_vars[ 'post_type' ] = array ( static::POST_TYPE_SLUG );
// Nothing else to do here.
return;
}
}
}
$prefixClassesRewrites = new PrefixClassesRewrites();
$prefixClassesRewrites(); // kick off the process
}
```
The thing is that nothing has changed, my url is not being rewritten. By the way, is the rewriting tule supposed to be in y htaccess when it's working? | Alright, I've changed my way of thinking about this issue and as I don't really know where the problem comes from I have opted for another solution.
**I am using a `wp_safe_redirect` to the url of the corresponding custom post type**.
For those interested in the solution, my form action is the `permalink` of a page created just for this (let's call it *class*).
On this *class* page I have the following safe redirect:
```
// getting my variables from the url
$language = get_query_var( '_language' );
$need = get_query_var( '_need' );
// redirecting to the corresponding custom post type url
if( isset( $language ) && isset( $need ) ) {
wp_safe_redirect( esc_url( home_url('/') ) .'class/'. $language .'-'. $need .'/', 301 );
exit;
} else {
// if variables are not defined
// redirect to home (or whatever page you want)
wp_safe_redirect( esc_url( home_url('/') ) );
exit;
}
```
Now everything works great! |
247,967 | <p>I have a custom post type 'University' on my website. Each university has post type 'Students'. So this is how it appears on hyperlinks: </p>
<p>www.abc.com/university/ali</p>
<p>now I want to make another university list and want the information to be displayed as </p>
<ul>
<li>www.abc.com/2015/university/ali </li>
<li>www.abc.com/2016/university/ali</li>
<li>www.abc.com/2017/university/ali</li>
</ul>
<p>How can I do that?</p>
| [
{
"answer_id": 248022,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 0,
"selected": false,
"text": "<p>Use '<a href=\"https://wordpress.org/plugins/custom-post-type-permalinks/\" rel=\"nofollow noreferrer\">custom... | 2016/11/30 | [
"https://wordpress.stackexchange.com/questions/247967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24020/"
] | I have a custom post type 'University' on my website. Each university has post type 'Students'. So this is how it appears on hyperlinks:
www.abc.com/university/ali
now I want to make another university list and want the information to be displayed as
* www.abc.com/2015/university/ali
* www.abc.com/2016/university/ali
* www.abc.com/2017/university/ali
How can I do that? | I have created 'project' posttype and 'project\_category' texonomy.Now you have to do is that go to add new project and add that project category that you want to show before your custom posttype name and permalink means add any post inside 2016 category.And set link as custom posttype '/%postname%/.try this code in your functions.php file and check .And do same with you custom posttype
I am getting this 'www.abc.com/2016/projects/test-permalink/'.
```
add_filter( 'pre_get_posts', 'query_post_type' );
function query_post_type( $query ) {
if ( is_category() ) {
$post_type = get_query_var( 'post_type' );
if ( $post_type ) {
$post_type = $post_type;
} else { $post_type = array( 'nav_menu_item', 'post', 'projects' ); // End if().
}
$query->set( 'post_type',$post_type );
return $query;
}
}
function custom_post_type() {
// Set UI labels for Custom Post Type
$labels = array(
'name' => _x( 'projects', 'Post Type General Name', 'namo' ),
'singular_name' => _x( 'projects', 'Post Type Singular Name', 'namo' ),
'menu_name' => __( 'projects', 'textdomain' ),
'parent_item_colon' => __( 'Parent projects', 'textdomain' ),
'all_items' => __( 'All projects', 'textdomain' ),
'view_item' => __( 'View projects', 'textdomain' ),
'add_new_item' => __( 'Add New projects', 'textdomain' ),
'add_new' => __( 'Add New', 'textdomain' ),
'edit_item' => __( 'Edit projects', 'textdomain' ),
'update_item' => __( 'Update projects', 'textdomain' ),
'search_items' => __( 'Search projects', 'textdomain' ),
'not_found' => __( 'Not Found', 'textdomain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'textdomain' ),
);
// Set other options for Custom Post Type
$args = array(
'label' => __( 'projects', 'textdomain' ),
'description' => __( 'projects news and reviews', 'textdomain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'rewrite' => array(
'slug' => '%project_category%/projects',
'with_front' => true,
),
// This is where we add taxonomies to our CPT
//'taxonomies' => array( 'category' ),
);
// Registering your Custom Post Type
register_post_type( 'projects', $args );
// Add new taxonomy, NOT hierarchical (like tags)
$labels = array(
'name' => _x( 'project_category', 'taxonomy general name', 'textdomain' ),
'singular_name' => _x( 'project_category', 'taxonomy singular name', 'textdomain' ),
'search_items' => __( 'Search project_categorys', 'textdomain' ),
'popular_items' => __( 'Popular project_categorys', 'textdomain' ),
'all_items' => __( 'All project_categorys', 'textdomain' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit project_category', 'textdomain' ),
'update_item' => __( 'Update project_category', 'textdomain' ),
'add_new_item' => __( 'Add New project_category', 'textdomain' ),
'new_item_name' => __( 'New project_category Name', 'textdomain' ),
'separate_items_with_commas' => __( 'Separate project_category with commas', 'namo' ),
'add_or_remove_items' => __( 'Add or remove project_category', 'namo' ),
'choose_from_most_used' => __( 'Choose from the most used project_category', 'namo' ),
'not_found' => __( 'No project_category found.', 'namo' ),
'menu_name' => __( 'project_category', 'namo' ),
);
$args1 = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
//'rewrite' => array( 'slug' => 'project_category' ),
'rewrite' => array(
'slug' => 'project_category',
'with_front' => true,
),
);
register_taxonomy( 'project_category', 'projects', $args1 );
}
add_action( 'init', 'custom_post_type', 0 );
function so23698827_add_rewrite_rules( $rules ) {
$new = array();
$new['([^/]+)/(.+)/?$/projects'] = 'index.php?projects=$matches[2]';
$new['(.+)/?$/projects'] = 'index.php?project_category=$matches[1]';
return array_merge( $new, $rules ); // Ensure our rules come first
}
add_filter( 'rewrite_rules_array', 'so23698827_add_rewrite_rules' );
function so23698827_filter_post_type_link( $link, $post ) {
if ( $post->post_type == 'projects' ) {
if ( $cats = get_the_terms( $post->ID, 'project_category' ) ) {
$link = str_replace( '%project_category%', current( $cats )->slug, $link );
}
}
return $link;
}
add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );
``` |
248,006 | <p>I have a problem with ACF plugin.</p>
<pre><code>function add_custom_post(/* .. */){}
$post_id = wp_insert_post(array(
//....
));
update_field('fieldname', $value, $post_id);
return (bool)$post_id;
}
</code></pre>
<p>Symptoms: <code><?php the_field('fieldname'); ?></code> does not return value in template;
Fields are saved and values are visible in wp-admin. After clicking "Update" to post, above starts working fine.<br>
From what I noticed it does not create post <code>key</code> if I use Update field and backoffice save creates them.</p>
<p>How to add value programmatically to newly added post?</p>
<p>EDIT:<br>
It would seem like i have to create <code>key</code> for field in post. No idea how.</p>
| [
{
"answer_id": 248007,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this instead of using <code>update_field()</code>:</p>\n\n<pre><code>update_post_meta($post_id, 'fiel... | 2016/12/01 | [
"https://wordpress.stackexchange.com/questions/248006",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108073/"
] | I have a problem with ACF plugin.
```
function add_custom_post(/* .. */){}
$post_id = wp_insert_post(array(
//....
));
update_field('fieldname', $value, $post_id);
return (bool)$post_id;
}
```
Symptoms: `<?php the_field('fieldname'); ?>` does not return value in template;
Fields are saved and values are visible in wp-admin. After clicking "Update" to post, above starts working fine.
From what I noticed it does not create post `key` if I use Update field and backoffice save creates them.
How to add value programmatically to newly added post?
EDIT:
It would seem like i have to create `key` for field in post. No idea how. | You can do this instead of using `update_field()`:
```
update_post_meta($post_id, 'fieldname', $value);
update_post_meta($post_id, '_fieldname', 'field_' . uniqid()); // `uniqid() is a native PHP function. This is also how ACF creates the field keys
```
Also, depending where you are retrieving the value, you may also have to pass the post id.
```
the_field('fieldname', $post_id);
``` |
248,011 | <p>I want to know that is it possible to fire a stored procedure once the plugin is activated? <br></p>
<pre><code>//action hook for plugin activation
register_activation_hook( __FILE__, 'my_func' );
//function to create stored procedure
function my_func()
{
//code goes here to create a stored procedure
}
</code></pre>
<p>Any help would be appreciated. Thank you.</p>
| [
{
"answer_id": 248007,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this instead of using <code>update_field()</code>:</p>\n\n<pre><code>update_post_meta($post_id, 'fiel... | 2016/12/01 | [
"https://wordpress.stackexchange.com/questions/248011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82089/"
] | I want to know that is it possible to fire a stored procedure once the plugin is activated?
```
//action hook for plugin activation
register_activation_hook( __FILE__, 'my_func' );
//function to create stored procedure
function my_func()
{
//code goes here to create a stored procedure
}
```
Any help would be appreciated. Thank you. | You can do this instead of using `update_field()`:
```
update_post_meta($post_id, 'fieldname', $value);
update_post_meta($post_id, '_fieldname', 'field_' . uniqid()); // `uniqid() is a native PHP function. This is also how ACF creates the field keys
```
Also, depending where you are retrieving the value, you may also have to pass the post id.
```
the_field('fieldname', $post_id);
``` |
248,026 | <p>I am using <a href="https://developer.wordpress.org/reference/functions/wp_dropdown_categories/" rel="nofollow noreferrer">wp_dropdown_categories</a> to create a dropdown in the frontend. It creates a nice dropdown select. Now I would like to add <code>onchange="myFunc()"</code> to the <code><select></code>. I need this to trigger some js function when someone selects specific option.</p>
<p>I also took a look into another <a href="https://codex.wordpress.org/Function_Reference/wp_dropdown_categories" rel="nofollow noreferrer">relevant codex link</a>, could not figure it out. Is there a native wordpress way of doing this ? If not, can you suggest me a solution. I mean something like this.</p>
<pre><code><select id="my_cats" class="postform" name="my_cats" onchange="myFunc()">
</code></pre>
| [
{
"answer_id": 248007,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this instead of using <code>update_field()</code>:</p>\n\n<pre><code>update_post_meta($post_id, 'fiel... | 2016/12/01 | [
"https://wordpress.stackexchange.com/questions/248026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25508/"
] | I am using [wp\_dropdown\_categories](https://developer.wordpress.org/reference/functions/wp_dropdown_categories/) to create a dropdown in the frontend. It creates a nice dropdown select. Now I would like to add `onchange="myFunc()"` to the `<select>`. I need this to trigger some js function when someone selects specific option.
I also took a look into another [relevant codex link](https://codex.wordpress.org/Function_Reference/wp_dropdown_categories), could not figure it out. Is there a native wordpress way of doing this ? If not, can you suggest me a solution. I mean something like this.
```
<select id="my_cats" class="postform" name="my_cats" onchange="myFunc()">
``` | You can do this instead of using `update_field()`:
```
update_post_meta($post_id, 'fieldname', $value);
update_post_meta($post_id, '_fieldname', 'field_' . uniqid()); // `uniqid() is a native PHP function. This is also how ACF creates the field keys
```
Also, depending where you are retrieving the value, you may also have to pass the post id.
```
the_field('fieldname', $post_id);
``` |
248,051 | <p>I've got the following code on my home page</p>
<pre><code><?php echo '<img class="img-responsive" src="',
wp_get_attachment_image_src( get_post_thumbnail_id(), 'Large' )[0], '">'; ?>
</code></pre>
<p>The large size in this case is 1920x245. This works fine in a browser but when the image scales down on smaller screens it's too thin for my taste. I would like to use an image with a different aspect ratio in that scenario.</p>
<p>How do I adjust the above php code to be responsive to media size? </p>
| [
{
"answer_id": 248048,
"author": "Tyler Johnson",
"author_id": 57451,
"author_profile": "https://wordpress.stackexchange.com/users/57451",
"pm_score": 1,
"selected": false,
"text": "<p>Honestly, the best way to do this is to run some queries on the database using regex to search and repl... | 2016/12/01 | [
"https://wordpress.stackexchange.com/questions/248051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101491/"
] | I've got the following code on my home page
```
<?php echo '<img class="img-responsive" src="',
wp_get_attachment_image_src( get_post_thumbnail_id(), 'Large' )[0], '">'; ?>
```
The large size in this case is 1920x245. This works fine in a browser but when the image scales down on smaller screens it's too thin for my taste. I would like to use an image with a different aspect ratio in that scenario.
How do I adjust the above php code to be responsive to media size? | Honestly, the best way to do this is to run some queries on the database using regex to search and replace, after the database has been backed up of course.
Before learning more about SQL, I used this: <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/>, which should work for you in this situation. You download the file, upload it to your public facing directory, and access the URL. Then you just use Regex to find the type of URLs you're looking for, and then specify the replacement. Run it, and you'll be good to go.
Don't forget to delete it after using it though, if you do use it! |
248,064 | <p>I have a wordpress website which I want to change, and it will takes me some months. My idea is create a subfolder in the root directory where I can set the a clone of my website to make some changes over it and at the same time keep the old website alive. </p>
<p>So if my website is:</p>
<pre><code>mysite.com
</code></pre>
<p>My developing clone will be:</p>
<pre><code>mysite.com/dev
</code></pre>
<p>The website is about news, so it has several posts which I want to keep. But I do not want to keep the media and plugins, so <code>/wp-content/plugins</code> and <code>/wp-content/uploads</code> will be empty. </p>
<p>I think that I have to use the same database to both sites because I want to keep the pasts posts and the posts that will be post along the developing time from the original website. So when I will finish the new website I just copy the files inside dev directory to the root directory. </p>
<p>So my question is, can I use the same database in two Wordpress sites where one of this is a developing clone?. A developing clone which I just want to keep the info but not the styles or media, and if I post a new post in the original site it will appear in the dev site too. </p>
| [
{
"answer_id": 248066,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 1,
"selected": false,
"text": "<p>I'd recommend against using the same database for both. Primarily because the permalink structure would real... | 2016/12/01 | [
"https://wordpress.stackexchange.com/questions/248064",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107058/"
] | I have a wordpress website which I want to change, and it will takes me some months. My idea is create a subfolder in the root directory where I can set the a clone of my website to make some changes over it and at the same time keep the old website alive.
So if my website is:
```
mysite.com
```
My developing clone will be:
```
mysite.com/dev
```
The website is about news, so it has several posts which I want to keep. But I do not want to keep the media and plugins, so `/wp-content/plugins` and `/wp-content/uploads` will be empty.
I think that I have to use the same database to both sites because I want to keep the pasts posts and the posts that will be post along the developing time from the original website. So when I will finish the new website I just copy the files inside dev directory to the root directory.
So my question is, can I use the same database in two Wordpress sites where one of this is a developing clone?. A developing clone which I just want to keep the info but not the styles or media, and if I post a new post in the original site it will appear in the dev site too. | I'd recommend against using the same database for both. Primarily because the permalink structure would really only work for one, but also because it's very likely you'd make a change in the dev site that adversely affects your production site. If you decided to attempt something like this, all your media would still be tied to it because media is added to your database the same way posts and pages are, but instead are called attachments.
I'd look into [WP Migrate DB](https://wordpress.org/plugins/wp-migrate-db/) to be able to pull in your site (or just your posts). However, you could simply [import](https://wordpress.org/plugins/wordpress-importer/) your old posts into a fresh install of Wordpress and go from there.
Good luck! |
248,146 | <p>i am using wordpress custom post and register_taxonomy bellow is my code .</p>
<pre>
<code>
function epg_works_register() {
$labels = array(
'name' => __('Works'),
'singular_name' => __('Works'),
'add_new' => __('Add Works Item'),
'add_new_item' => __('Add New Works Item'),
'edit_item' => __('Edit Works Item'),
'new_item' => __('New Works Item'),
'view_item' => __('View Works Item'),
'search_items' => __('Search Works Item'),
'not_found' => __('No Works Items found'),
'not_found_in_trash' => __('No Works Items found in Trash'),
'parent_item_colon' => '',
'menu_name' => __('Works')
);
// Set other options for Custom Post Type
$args = array(
'labels' => $labels,
// Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor'),
/* A hierarchical CPT is like Pages and can have
* Parent and child items. A non-hierarchical CPT
* is like Posts.
*/
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'capability_type' => 'post',
);
// Registering your Custom Post Type
register_post_type( 'works', $args );
register_taxonomy('works_category', 'works', array('hierarchical' => true, 'label' => 'Works Category', 'query_var' => true, 'rewrite' => array('slug' => 'works-categorys')));
flush_rewrite_rules();
}
add_action( 'init', 'epg_works_register');
</code>
</pre>
<p>if i am changeing register_taxonomy('works_category' to register_taxonomy('something ') it's show on <a href="http://localhost/wp-admin/nav-menus.php" rel="nofollow noreferrer">http://localhost/wp-admin/nav-menus.php</a> </p>
<p>but if used register_taxonomy('works_category') then i can't see anything there <a href="http://localhost/wp-admin/nav-menus.php" rel="nofollow noreferrer">http://localhost/wp-admin/nav-menus.php</a>.</p>
<p>What's wrong ? </p>
<p>Thanks</p>
| [
{
"answer_id": 248152,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": true,
"text": "<p>The only thing that I see is the argument <code>'query_var'=>true</code>, it can be set to false, but the de... | 2016/12/02 | [
"https://wordpress.stackexchange.com/questions/248146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83449/"
] | i am using wordpress custom post and register\_taxonomy bellow is my code .
```
function epg_works_register() {
$labels = array(
'name' => __('Works'),
'singular_name' => __('Works'),
'add_new' => __('Add Works Item'),
'add_new_item' => __('Add New Works Item'),
'edit_item' => __('Edit Works Item'),
'new_item' => __('New Works Item'),
'view_item' => __('View Works Item'),
'search_items' => __('Search Works Item'),
'not_found' => __('No Works Items found'),
'not_found_in_trash' => __('No Works Items found in Trash'),
'parent_item_colon' => '',
'menu_name' => __('Works')
);
// Set other options for Custom Post Type
$args = array(
'labels' => $labels,
// Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor'),
/* A hierarchical CPT is like Pages and can have
* Parent and child items. A non-hierarchical CPT
* is like Posts.
*/
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'capability_type' => 'post',
);
// Registering your Custom Post Type
register_post_type( 'works', $args );
register_taxonomy('works_category', 'works', array('hierarchical' => true, 'label' => 'Works Category', 'query_var' => true, 'rewrite' => array('slug' => 'works-categorys')));
flush_rewrite_rules();
}
add_action( 'init', 'epg_works_register');
```
if i am changeing register\_taxonomy('works\_category' to register\_taxonomy('something ') it's show on <http://localhost/wp-admin/nav-menus.php>
but if used register\_taxonomy('works\_category') then i can't see anything there <http://localhost/wp-admin/nav-menus.php>.
What's wrong ?
Thanks | The only thing that I see is the argument `'query_var'=>true`, it can be set to false, but the default value is the taxonomy name, so set it to true is maybe the cause of the failure, even the codex example set it to true, I think it can be great to try
```
register_taxonomy(
'works_category',
'works',
array(
'hierarchical' => true,
'label' => 'Works Category',
'query_var' => 'works_category',
'rewrite' => array('slug' => 'works-categorys')
)
);
```
Or just suppress query\_var from the array ? |
248,149 | <p>In chrome, firefox everything is fine.</p>
<p>On mobile ios safari it looks like the pic. The columns won't collapse into rows.</p>
<p>Tried the guide but didn't seem to work
<a href="https://css-tricks.com/accessible-simple-responsive-tables/" rel="nofollow noreferrer">https://css-tricks.com/accessible-simple-responsive-tables/</a></p>
<p>I've tried</p>
<p>-setting to display:block to collapse columns into rows on responsive mobile.
-setting css for tr to display:table-row, width:100%; and setting td to display: table-row</p>
<p>The html is..</p>
<pre><code><tr class="cart-item">
<td class="name"><a>productname</a></td>
<td class="price"><a>number</a></td>
<td class="quantity"><a>number</a></td>
<td class="total"><a>number</a></td>
</tr>
</code></pre>
<p>The CSS is.. </p>
<pre><code>.woocommerce table.shop_table_responsive tr td {
display: table-row;
}
.woocommerce table.shop_table_responsive tr {
display: table;
width: 100%;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/ghJt7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ghJt7.png" alt="cart page on iphone6"></a></p>
| [
{
"answer_id": 248175,
"author": "Rosenbruger",
"author_id": 108057,
"author_profile": "https://wordpress.stackexchange.com/users/108057",
"pm_score": 1,
"selected": false,
"text": "<p>I know it's bad practice to use !important frequently but you could use it on any style that's not show... | 2016/12/02 | [
"https://wordpress.stackexchange.com/questions/248149",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102722/"
] | In chrome, firefox everything is fine.
On mobile ios safari it looks like the pic. The columns won't collapse into rows.
Tried the guide but didn't seem to work
<https://css-tricks.com/accessible-simple-responsive-tables/>
I've tried
-setting to display:block to collapse columns into rows on responsive mobile.
-setting css for tr to display:table-row, width:100%; and setting td to display: table-row
The html is..
```
<tr class="cart-item">
<td class="name"><a>productname</a></td>
<td class="price"><a>number</a></td>
<td class="quantity"><a>number</a></td>
<td class="total"><a>number</a></td>
</tr>
```
The CSS is..
```
.woocommerce table.shop_table_responsive tr td {
display: table-row;
}
.woocommerce table.shop_table_responsive tr {
display: table;
width: 100%;
}
```
[](https://i.stack.imgur.com/ghJt7.png) | I know it's bad practice to use !important frequently but you could use it on any style that's not showing just to check if your theme is overriding your code. |
248,168 | <p>I'm encountering a strange issue with WordPress. I'm building a theme and the theme customization is driven by Customizer.</p>
<p>So, basically in functions.php I'm adding</p>
<pre><code>add_theme_support( 'widget-customizer' );
</code></pre>
<p>i'm registering a sidebar with:</p>
<pre><code>register_sidebar( array(
'name' => __( 'Test Sidebar' ),
'id' => 'test-sidebar',
));
</code></pre>
<p>then in <strong>index.php</strong> i'm adding the common <strong><em>get_footer();</em></strong> and in <strong><em>footer.php</em></strong> I have:</p>
<pre><code><?php if ( is_active_sidebar( 'test-sidebar' ) ): ?>
<div id="test-sidebar" class="sidebar">
<?php dynamic_sidebar( 'test-sidebar' ); ?>
</div>
<?php endif; ?>
</code></pre>
<p>Now the <strong>first</strong> strange issue is that in the preview window I can see any widget added via admin page in <em>Appearance</em> but in the customizer widget section I can't see any area and I get this message</p>
<blockquote>
<p>There are no widget areas currently rendered in the preview. Navigate
in the preview to a template that makes use of a widget area in order
to access its widgets here.</p>
</blockquote>
<p>But the <strong>second</strong> strange issue is that if in my functions.php I add:</p>
<pre><code> add_action( 'wp_footer', function () {
?>
<?php if ( is_active_sidebar( 'test-sidebar' ) ): ?>
<div id="test-sidebar" class="sidebar">
<?php dynamic_sidebar( 'test-sidebar' ); ?>
</div>
<?php endif; ?>
<?php
} );
</code></pre>
<p>Now I can see the widget area in customizer. </p>
<p>What could be the problem?</p>
| [
{
"answer_id": 248175,
"author": "Rosenbruger",
"author_id": 108057,
"author_profile": "https://wordpress.stackexchange.com/users/108057",
"pm_score": 1,
"selected": false,
"text": "<p>I know it's bad practice to use !important frequently but you could use it on any style that's not show... | 2016/12/03 | [
"https://wordpress.stackexchange.com/questions/248168",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108200/"
] | I'm encountering a strange issue with WordPress. I'm building a theme and the theme customization is driven by Customizer.
So, basically in functions.php I'm adding
```
add_theme_support( 'widget-customizer' );
```
i'm registering a sidebar with:
```
register_sidebar( array(
'name' => __( 'Test Sidebar' ),
'id' => 'test-sidebar',
));
```
then in **index.php** i'm adding the common ***get\_footer();*** and in ***footer.php*** I have:
```
<?php if ( is_active_sidebar( 'test-sidebar' ) ): ?>
<div id="test-sidebar" class="sidebar">
<?php dynamic_sidebar( 'test-sidebar' ); ?>
</div>
<?php endif; ?>
```
Now the **first** strange issue is that in the preview window I can see any widget added via admin page in *Appearance* but in the customizer widget section I can't see any area and I get this message
>
> There are no widget areas currently rendered in the preview. Navigate
> in the preview to a template that makes use of a widget area in order
> to access its widgets here.
>
>
>
But the **second** strange issue is that if in my functions.php I add:
```
add_action( 'wp_footer', function () {
?>
<?php if ( is_active_sidebar( 'test-sidebar' ) ): ?>
<div id="test-sidebar" class="sidebar">
<?php dynamic_sidebar( 'test-sidebar' ); ?>
</div>
<?php endif; ?>
<?php
} );
```
Now I can see the widget area in customizer.
What could be the problem? | I know it's bad practice to use !important frequently but you could use it on any style that's not showing just to check if your theme is overriding your code. |
248,182 | <p>All around the Interwebs I see advice from people who say that when you want to get posts in a custom taxonomy you should use the filter parameter, for example:</p>
<pre><code>https://example.com/wp-json/wp/v2/posts?filter[genre]=fiction
</code></pre>
<p>This seems like a very handy parameter. But in v2 of the WP REST API it just doesn't work. When I created a WP Trac ticket to find out what was going on, @swissspidy responded that "the filter param has been removed on purpose" but that the documentation hasn't been updated yet. The change is discussed in <a href="https://core.trac.wordpress.org/ticket/38378" rel="noreferrer">Trac ticket 38378</a>.</p>
<p>OK, fair enough, but could someone tell me how I should retrieve posts in a custom taxonomy now? I'm writing a plugin that depends on being able to do this.</p>
<p>For example, if I've created a non-hierarchical custom taxonomy <code>instance</code> and given it the value <code>1</code> for certain posts in a custom post type, how can I retrieve all the posts of that type and with <code>instance=1</code>?</p>
<p>If it's not possible via the REST API, is there a way to do it via the WordPress.com API on a Jetpack-enabled self-hosted site?</p>
| [
{
"answer_id": 248175,
"author": "Rosenbruger",
"author_id": 108057,
"author_profile": "https://wordpress.stackexchange.com/users/108057",
"pm_score": 1,
"selected": false,
"text": "<p>I know it's bad practice to use !important frequently but you could use it on any style that's not show... | 2016/12/03 | [
"https://wordpress.stackexchange.com/questions/248182",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14984/"
] | All around the Interwebs I see advice from people who say that when you want to get posts in a custom taxonomy you should use the filter parameter, for example:
```
https://example.com/wp-json/wp/v2/posts?filter[genre]=fiction
```
This seems like a very handy parameter. But in v2 of the WP REST API it just doesn't work. When I created a WP Trac ticket to find out what was going on, @swissspidy responded that "the filter param has been removed on purpose" but that the documentation hasn't been updated yet. The change is discussed in [Trac ticket 38378](https://core.trac.wordpress.org/ticket/38378).
OK, fair enough, but could someone tell me how I should retrieve posts in a custom taxonomy now? I'm writing a plugin that depends on being able to do this.
For example, if I've created a non-hierarchical custom taxonomy `instance` and given it the value `1` for certain posts in a custom post type, how can I retrieve all the posts of that type and with `instance=1`?
If it's not possible via the REST API, is there a way to do it via the WordPress.com API on a Jetpack-enabled self-hosted site? | I know it's bad practice to use !important frequently but you could use it on any style that's not showing just to check if your theme is overriding your code. |
248,207 | <p>I have a wordpress installation and I need this query on every post:</p>
<pre><code>select post_id, meta_key from wp_postmeta where meta_key = 'mykey' and meta_value = 'somevalue'
</code></pre>
<p>I have 3M rows on that table, and the query takes about 6 sec to complete. I think it should be much faster. If I show the index of the table, it returns me:</p>
<pre><code>SHOW INDEX FROM wp_postmeta
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment Index_comment
wp_postmeta 0 PRIMARY 1 meta_id A 3437260 NULL NULL BTREE
wp_postmeta 1 post_id 1 post_id A 1718630 NULL NULL BTREE
wp_postmeta 1 meta_key 1 meta_key A 29 191 NULL YES BTREE
</code></pre>
<p>If I make a explain, it returns me this:</p>
<pre><code>explain select post_id, meta_key from wp_postmeta where meta_key = 'mykey' and meta_value = 'somevalue'
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE wp_postmeta ref meta_key meta_key 767 const 597392 Using where
</code></pre>
<p>I'm not very good in mysql so I don't know how to check or solve it. Can you give me some orientation on where the problem is??</p>
<p>Thanks you all.</p>
| [
{
"answer_id": 280957,
"author": "Rick James",
"author_id": 120226,
"author_profile": "https://wordpress.stackexchange.com/users/120226",
"pm_score": 2,
"selected": false,
"text": "<p><code>wp_postmeta</code> has inefficient indexes. The published table (see Wikipedia) is </p>\n\n<pre><... | 2016/12/03 | [
"https://wordpress.stackexchange.com/questions/248207",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105492/"
] | I have a wordpress installation and I need this query on every post:
```
select post_id, meta_key from wp_postmeta where meta_key = 'mykey' and meta_value = 'somevalue'
```
I have 3M rows on that table, and the query takes about 6 sec to complete. I think it should be much faster. If I show the index of the table, it returns me:
```
SHOW INDEX FROM wp_postmeta
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment Index_comment
wp_postmeta 0 PRIMARY 1 meta_id A 3437260 NULL NULL BTREE
wp_postmeta 1 post_id 1 post_id A 1718630 NULL NULL BTREE
wp_postmeta 1 meta_key 1 meta_key A 29 191 NULL YES BTREE
```
If I make a explain, it returns me this:
```
explain select post_id, meta_key from wp_postmeta where meta_key = 'mykey' and meta_value = 'somevalue'
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE wp_postmeta ref meta_key meta_key 767 const 597392 Using where
```
I'm not very good in mysql so I don't know how to check or solve it. Can you give me some orientation on where the problem is??
Thanks you all. | `wp_postmeta` has inefficient indexes. The published table (see Wikipedia) is
```
CREATE TABLE wp_postmeta (
meta_id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
post_id bigint(20) unsigned NOT NULL DEFAULT '0',
meta_key varchar(255) DEFAULT NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY post_id (post_id),
KEY meta_key (meta_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
The problems:
* The `AUTO_INCREMENT` provides no benefit; in fact it slows down most queries (because of having to look in secondary index to find auto\_inc id, then looking in data for actual id you need)
* The `AUTO_INCREMENT` is extra clutter - both on disk and in cache.
* Much better is `PRIMARY KEY(post_id, meta_key)` -- clustered, handles both parts of usual `JOIN`.
* `BIGINT` is overkill, but that can't be fixed without changing other tables.
* `VARCHAR(255)` can be a problem in MySQL 5.6 with `utf8mb4`; see workarounds below.
* When would meta\_key or meta\_value ever be `NULL`?
The solutions:
```
CREATE TABLE wp_postmeta (
post_id BIGINT UNSIGNED NOT NULL,
meta_key VARCHAR(255) NOT NULL,
meta_value LONGTEXT NOT NULL,
PRIMARY KEY(post_id, meta_key),
INDEX(meta_key)
) ENGINE=InnoDB;
```
The typical usage:
```
JOIN wp_postmeta AS m ON p.id = m.post_id
WHERE m.meta_key = '...'
```
Notes:
* The composite `PRIMARY KEY` goes straight to the desired row, no digression through secondary index, nor search through multiple rows.
* `INDEX(meta_key)` may or may not be useful, depending on what other queries you have.
* InnoDB is required for the 'clustering'.
* Going forward, use utf8mb4, not utf8. However, you should be consistent across all WP tables and in your connection parameters.
The error "max key length is 767", which can happen in MySQL 5.6 when trying to use CHARACTER SET utf8mb4. Do one of the following (each has a drawback) to avoid the error:
* Upgrade to 5.7.7 for 3072 byte limit -- your cloud may not provide this;
* Change 255 to 191 on the VARCHAR -- you lose any keys longer than 191 characters (unlikely?);
* ALTER .. CONVERT TO utf8 -- you lose Emoji and some of Chinese;
* Use a "prefix" index -- you lose some of the performance benefits;
* Reconfigure (if staying with 5.6.3 - 5.7.6) -- 4 things to change: Barracuda + innodb\_file\_per\_table + innodb\_large\_prefix + dynamic or compressed.
**Potential incompatibilities**
* `meta_id` is probably not used anywhere. (But it is a risk to remove it).
* You could keep `meta_id` and get most of the benefits by changing to these indexes: `PRIMARY KEY(post_id, meta_key, meta_id), INDEX(meta_id), INDEX(meta_key, post_id)`. (Note: By having `meta_id` on the end of the PK, it is possible for post\_id+meta\_key to be non-unique.)
* Changing from `BIGINT` to a smaller datatype would involve changing other tables, too.
**utf8mb4**
* Moving to 5.7 should not be incompatible.
* Shrinking to `VARCHAR(191)` would require the user to understand that the limit is now the arbitrary "191" instead of the previous arbitrary limit of "255".
* The 'reconfigure' fix is DBA issues, not incompatibility issues.
**Comment**
I hope that some of what I advocate is on the WordPress roadmap. Meanwhile, stackoverflow and dba.stackexchange are cluttered with "why is WP running so slow". I believe that the fixes given here would cut back significantly in such complaint-type Questions.
Note that some users are changing to utf8mb4 in spite of compatibility issues. Then they get in trouble. I have tried to address all the *MySQL* issues they are having.
Taken from Rick James mysql blog: [source](http://mysql.rjweb.org/doc.php/index_cookbook_mysql#speeding_up_wp_postmeta) |
248,276 | <p>I want to make a user-create snippet, but it must not includes plain password.</p>
<pre><code> $ wp user create username username@example.com --role=administrator --user_pass=password
</code></pre>
<p>So can I create (or update) user password by hashed value?</p>
| [
{
"answer_id": 248321,
"author": "thebigtine",
"author_id": 76059,
"author_profile": "https://wordpress.stackexchange.com/users/76059",
"pm_score": 2,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>wp user update USERNAME --user_pass=PASSWORD\n</code></pre>\n\n<p>Foun... | 2016/12/05 | [
"https://wordpress.stackexchange.com/questions/248276",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108292/"
] | I want to make a user-create snippet, but it must not includes plain password.
```
$ wp user create username username@example.com --role=administrator --user_pass=password
```
So can I create (or update) user password by hashed value? | There is not "one command" in Wordpress CLI that does the job: <https://github.com/wp-cli/wp-cli/issues/2270>
However using other commands, you can overide the user password directly in the database using the following:
```
USER_ID=$(wp user list --login="$USR_LOGIN" --format=ids)
wp db query "UPDATE wp_users SET user_pass='$HASHED_PASS' WHERE ID = $USER_ID;"
```
First line is optional if you already know the user ID.
To hash a password, use the following:
```
wp eval "echo wp_hash_password('$CLEAR_PASSWORD');"
``` |
248,279 | <p>I'd like to redirect user to login page on specific pages, after displaying message "You need to login to view this page".
I followed this documentation, but couldn't get through. <a href="https://codex.wordpress.org/Function_Reference/auth_redirect" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/auth_redirect</a></p>
| [
{
"answer_id": 248280,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 0,
"selected": false,
"text": "<p>It works fine in our file, will you please give us bit of code in which filter or action you are running this ... | 2016/12/05 | [
"https://wordpress.stackexchange.com/questions/248279",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94247/"
] | I'd like to redirect user to login page on specific pages, after displaying message "You need to login to view this page".
I followed this documentation, but couldn't get through. <https://codex.wordpress.org/Function_Reference/auth_redirect> | You can do it like this in admin section-
```
add_action( 'admin_init', 'redirect_non_logged_users_to_specific_page' );
function redirect_non_logged_users_to_specific_page() {
if ( !is_user_logged_in() && is_page('add page slug or i.d here') &&
$_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {
wp_redirect( 'http://www.example.dev/page/' );
exit;
}
```
And for frontend-
```
add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
if ( is_page('slug') && ! is_user_logged_in() ) {
wp_redirect( 'http://www.example.dev/your-page/', 301 );
exit;
}
}
```
And this `auth_redirect` function is for backend. If you want to use it on front end then add the below filter-
```
add_filter( 'auth_redirect_scheme', 'the_dramatistcheck_loggedin' );
function the_dramatist_check_loggedin(){
return 'logged_in';
}
```
Then `auth_redirect()` will work as expected : redirect users to the login form if they are not logged in. |
248,311 | <p>I know how it is possible to wrap HTML around anchor elements with the inbuilt arguments for <code>wp_get_archives</code>. Is there a way to alter the content of the anchors in order to add a wrapping span for the anchor text?
The intention is to use it for a list of yearly archives on a category (i.e. an automated list of years for which posts exist). </p>
<p>Before:</p>
<pre><code><ul>
<li><a href="xx">2014</a></li>
<li><a href="xx">2015</a></li>
<li><a href="xx">2016</a></li>
</ul>
</code></pre>
<p>After:</p>
<pre><code><ul>
<li><a href="xx"><span>2014</span></a></li>
<li><a href="xx"><span>2015</span></a></li>
<li><a href="xx"><span>2016</span></a></li>
</ul>
</code></pre>
| [
{
"answer_id": 248313,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<h2>Span outside anchor tags</h2>\n\n<p>I think you're looking for the <code>before</code> and <code>after</code>... | 2016/12/05 | [
"https://wordpress.stackexchange.com/questions/248311",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25245/"
] | I know how it is possible to wrap HTML around anchor elements with the inbuilt arguments for `wp_get_archives`. Is there a way to alter the content of the anchors in order to add a wrapping span for the anchor text?
The intention is to use it for a list of yearly archives on a category (i.e. an automated list of years for which posts exist).
Before:
```
<ul>
<li><a href="xx">2014</a></li>
<li><a href="xx">2015</a></li>
<li><a href="xx">2016</a></li>
</ul>
```
After:
```
<ul>
<li><a href="xx"><span>2014</span></a></li>
<li><a href="xx"><span>2015</span></a></li>
<li><a href="xx"><span>2016</span></a></li>
</ul>
``` | Span outside anchor tags
------------------------
I think you're looking for the `before` and `after` arguments (*PHP 5.4+*):
```
wp_get_archives(
[
'before' => '<span>',
'after' => '</span>'
]
);
```
if you want to wrap the `<span>` tag around the `<a>` tag:
```
<li><span><a href="xx">Link text</a></span></li>
```
Span inside anchor tags
-----------------------
If you want it inside the anchor tags:
```
<li><a href="xx"><span>Link text</span></a></li>
```
then you could use the `get_archives_link` filter to reconstruct the links to your needs.
Modify the corresponding theme file with (*PHP 5.4+*):
```
// Add a custom filter
add_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );
// Archive
wp_get_archives(
[
'type' => 'yearly', // For yearly archive
'format' => 'html' // This is actually a default setting
]
); // EDIT the arguments to your needs (I'm not showing the <ul> part here)
// Remove the custom filter
remove_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );
```
where our filter callback is defined, in the `functions.php` file in the current theme directory, as:
```
function wpse_get_archives_link( $link_html, $url, $text, $format, $before, $after )
{
if( 'html' === $format )
$link_html = "\t<li>$before<a href='$url'><span>$text</span></a>$after</li>\n";
return $link_html;
}
```
where we've added the span inside the anchor tag. |
248,332 | <p>I need change the tagline to a custom, specific tagline, further describing my business such as - "self-funded revenue increase" but I can't find it.</p>
| [
{
"answer_id": 248313,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<h2>Span outside anchor tags</h2>\n\n<p>I think you're looking for the <code>before</code> and <code>after</code>... | 2016/12/05 | [
"https://wordpress.stackexchange.com/questions/248332",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108330/"
] | I need change the tagline to a custom, specific tagline, further describing my business such as - "self-funded revenue increase" but I can't find it. | Span outside anchor tags
------------------------
I think you're looking for the `before` and `after` arguments (*PHP 5.4+*):
```
wp_get_archives(
[
'before' => '<span>',
'after' => '</span>'
]
);
```
if you want to wrap the `<span>` tag around the `<a>` tag:
```
<li><span><a href="xx">Link text</a></span></li>
```
Span inside anchor tags
-----------------------
If you want it inside the anchor tags:
```
<li><a href="xx"><span>Link text</span></a></li>
```
then you could use the `get_archives_link` filter to reconstruct the links to your needs.
Modify the corresponding theme file with (*PHP 5.4+*):
```
// Add a custom filter
add_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );
// Archive
wp_get_archives(
[
'type' => 'yearly', // For yearly archive
'format' => 'html' // This is actually a default setting
]
); // EDIT the arguments to your needs (I'm not showing the <ul> part here)
// Remove the custom filter
remove_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );
```
where our filter callback is defined, in the `functions.php` file in the current theme directory, as:
```
function wpse_get_archives_link( $link_html, $url, $text, $format, $before, $after )
{
if( 'html' === $format )
$link_html = "\t<li>$before<a href='$url'><span>$text</span></a>$after</li>\n";
return $link_html;
}
```
where we've added the span inside the anchor tag. |
248,343 | <p>I am the owner of a small company that makes wordpress websites for entrepeneurs. When we go to a customer, we want to show some examples of themes we could be going to use. We want the themes to display some information of the customer, like a logo. a header title and some personal information. We will probably be adding this information through the Customizer of the theme(s).</p>
<p>This will result in 3 different themes with identical information.</p>
<p>We can make 3 different databases and change <code>the wp-config.php</code> file to the right database name when we want to show a different theme, but we were wondering if there was another solution?</p>
<p>We only have 1 domain available, so it's not possible to put each theme on a different domain..</p>
| [
{
"answer_id": 248313,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<h2>Span outside anchor tags</h2>\n\n<p>I think you're looking for the <code>before</code> and <code>after</code>... | 2016/12/05 | [
"https://wordpress.stackexchange.com/questions/248343",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108345/"
] | I am the owner of a small company that makes wordpress websites for entrepeneurs. When we go to a customer, we want to show some examples of themes we could be going to use. We want the themes to display some information of the customer, like a logo. a header title and some personal information. We will probably be adding this information through the Customizer of the theme(s).
This will result in 3 different themes with identical information.
We can make 3 different databases and change `the wp-config.php` file to the right database name when we want to show a different theme, but we were wondering if there was another solution?
We only have 1 domain available, so it's not possible to put each theme on a different domain.. | Span outside anchor tags
------------------------
I think you're looking for the `before` and `after` arguments (*PHP 5.4+*):
```
wp_get_archives(
[
'before' => '<span>',
'after' => '</span>'
]
);
```
if you want to wrap the `<span>` tag around the `<a>` tag:
```
<li><span><a href="xx">Link text</a></span></li>
```
Span inside anchor tags
-----------------------
If you want it inside the anchor tags:
```
<li><a href="xx"><span>Link text</span></a></li>
```
then you could use the `get_archives_link` filter to reconstruct the links to your needs.
Modify the corresponding theme file with (*PHP 5.4+*):
```
// Add a custom filter
add_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );
// Archive
wp_get_archives(
[
'type' => 'yearly', // For yearly archive
'format' => 'html' // This is actually a default setting
]
); // EDIT the arguments to your needs (I'm not showing the <ul> part here)
// Remove the custom filter
remove_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );
```
where our filter callback is defined, in the `functions.php` file in the current theme directory, as:
```
function wpse_get_archives_link( $link_html, $url, $text, $format, $before, $after )
{
if( 'html' === $format )
$link_html = "\t<li>$before<a href='$url'><span>$text</span></a>$after</li>\n";
return $link_html;
}
```
where we've added the span inside the anchor tag. |
248,357 | <p>In a page, I need to display a list of all sub categories of a specify category.</p>
<p>For example, in the category <em>Sport</em> have 6 subcategories:</p>
<blockquote>
<ul>
<li>Swim</li>
<li>Football</li>
<li>Basket</li>
<li>Ski</li>
<li>Hockey</li>
</ul>
</blockquote>
<p>Each subcategory has a featured image, title and description, which I'd like to display.</p>
<p>I've add featured image using this code (in functions.php):</p>
<pre><code>add_action('init', 'my_category_module');
function my_category_module() {
add_action ( 'edit_category_form_fields', 'add_image_cat');
add_action ( 'edited_category', 'save_image');
}
function add_image_cat($tag){
$category_images = get_option( 'category_images' );
$category_image = '';
if ( is_array( $category_images ) && array_key_exists( $tag->term_id, $category_images ) ) {
$category_image = $category_images[$tag->term_id] ;
}
?>
<tr>
<th scope="row" valign="top"><label for="auteur_revue_image">Image</label></th>
<td>
<?php
if ($category_image !=""){
?>
<img src="<?php echo $category_image;?>" alt="" title=""/>
<?php
}
?>
<br/>
<input type="text" name="category_image" id="category_image" value="<?php echo $category_image; ?>"/><br />
<span>This field allows you to add a picture to illustrate the category. Upload the image from the media tab WordPress and paste its URL here.</span>
</td>
</tr>
<?php
}
function save_image($term_id){
if ( isset( $_POST['category_image'] ) ) {
//load existing category featured option
$category_images = get_option( 'category_images' );
//set featured post ID to proper category ID in options array
$category_images[$term_id] = $_POST['category_image'];
//save the option array
update_option( 'category_images', $category_images );
}
}
</code></pre>
<p><strong>category.php</strong></p>
<pre><code><?php
if(is_category()){
$category_images = get_option( 'category_images' );
$category_image = '';
if ( is_array( $category_images ) && array_key_exists( get_query_var('cat'), $category_images ) ){
$category_image = $category_images[get_query_var('cat')] ;
?>
<img src="<?php echo $category_image;?>"/>
<?php
}
}
?>
</code></pre>
<p>I need to have a grid look like this (this is for recent post )</p>
<p>With this I can display all categories with their descriptions, but how can I add the featured image and display only subcategories of certain category parent?</p>
<pre><code><?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC'
) );
foreach( $categories as $category ) {
$category_link = sprintf(
'<a href="%1$s" alt="%2$s">%3$s</a>',
esc_url( get_category_link( $category->term_id ) ),
esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
esc_html( $category->name )
);
echo '<p>' . sprintf( esc_html__( 'Category: %s', 'textdomain' ), $category_link ) . '</p> ';
echo '<p>' . sprintf( esc_html__( 'Description: %s', 'textdomain' ), $category->description ) . '</p>';}
</code></pre>
<p>Also is possible to display as a grid?</p>
<p>Thanks</p>
| [
{
"answer_id": 259174,
"author": "ricotheque",
"author_id": 34238,
"author_profile": "https://wordpress.stackexchange.com/users/34238",
"pm_score": 1,
"selected": false,
"text": "<p><strong>How can I add the featured image?</strong></p>\n\n<p>From what I can tell in your code, you've sto... | 2016/12/05 | [
"https://wordpress.stackexchange.com/questions/248357",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51160/"
] | In a page, I need to display a list of all sub categories of a specify category.
For example, in the category *Sport* have 6 subcategories:
>
> * Swim
> * Football
> * Basket
> * Ski
> * Hockey
>
>
>
Each subcategory has a featured image, title and description, which I'd like to display.
I've add featured image using this code (in functions.php):
```
add_action('init', 'my_category_module');
function my_category_module() {
add_action ( 'edit_category_form_fields', 'add_image_cat');
add_action ( 'edited_category', 'save_image');
}
function add_image_cat($tag){
$category_images = get_option( 'category_images' );
$category_image = '';
if ( is_array( $category_images ) && array_key_exists( $tag->term_id, $category_images ) ) {
$category_image = $category_images[$tag->term_id] ;
}
?>
<tr>
<th scope="row" valign="top"><label for="auteur_revue_image">Image</label></th>
<td>
<?php
if ($category_image !=""){
?>
<img src="<?php echo $category_image;?>" alt="" title=""/>
<?php
}
?>
<br/>
<input type="text" name="category_image" id="category_image" value="<?php echo $category_image; ?>"/><br />
<span>This field allows you to add a picture to illustrate the category. Upload the image from the media tab WordPress and paste its URL here.</span>
</td>
</tr>
<?php
}
function save_image($term_id){
if ( isset( $_POST['category_image'] ) ) {
//load existing category featured option
$category_images = get_option( 'category_images' );
//set featured post ID to proper category ID in options array
$category_images[$term_id] = $_POST['category_image'];
//save the option array
update_option( 'category_images', $category_images );
}
}
```
**category.php**
```
<?php
if(is_category()){
$category_images = get_option( 'category_images' );
$category_image = '';
if ( is_array( $category_images ) && array_key_exists( get_query_var('cat'), $category_images ) ){
$category_image = $category_images[get_query_var('cat')] ;
?>
<img src="<?php echo $category_image;?>"/>
<?php
}
}
?>
```
I need to have a grid look like this (this is for recent post )
With this I can display all categories with their descriptions, but how can I add the featured image and display only subcategories of certain category parent?
```
<?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC'
) );
foreach( $categories as $category ) {
$category_link = sprintf(
'<a href="%1$s" alt="%2$s">%3$s</a>',
esc_url( get_category_link( $category->term_id ) ),
esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
esc_html( $category->name )
);
echo '<p>' . sprintf( esc_html__( 'Category: %s', 'textdomain' ), $category_link ) . '</p> ';
echo '<p>' . sprintf( esc_html__( 'Description: %s', 'textdomain' ), $category->description ) . '</p>';}
```
Also is possible to display as a grid?
Thanks | **How can I add the featured image?**
From what I can tell in your code, you've stored all category featured images in the `category_images` option. So you can use `get_option` to retrieve the featured image for each category:
```
$image_urls = get_option( 'category_images', array() );
foreach ( $categories as $category ) {
$cat_id = $category->term_id;
$image_url = isset( $image_urls[$cat_id ) ? $image_urls[$cat_id] : '';
...
}
```
You can then use `$image_url` as the `src` attribute of an `<img>`.
**How can I display only the subcategories of a certain category parent?**
Like `get_terms`, `get_categories` has a 'child\_of' parameter. Again, in your `foreach` loop:
```
$sub_categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'child_of' => $cat_id,
) );
foreach ( $sub_categories as $sub_category ) {
// Process the sub-categories here.
}
```
**Is it possible to display these as a grid?**
Yes, you can! But that's an [HTML/CSS question](https://stackoverflow.com/questions/tagged/css) that I think is beyond the scope of this question. Go ahead and open a new question under that topic. You can never ask too many. :)
Hope this helps! |
248,367 | <p><br />I want to call the wordpress media uploader with a button in my theme options page. The thing is that I need three upload media buttons on the same page. I'm trying to do that using jQuery multiple IDs selector. The code is working fine: I click the button and the media uploader is launched, however when I upload anything into the first input field, the media that I just uploaded is passed on to the other input fields in the page. Like they were binded together. Sorry for the stupid question, I dont know much JavaScript. But anyways, how can I fix this??</p>
<pre><code>jQuery(document).ready(function( $) {
var mediaUploader;
$('#upload-button-1, #upload-button-2, #upload-button-3').on('click', function(e) {
e.preventDefault();
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Upload',
button: {
text: 'Upload'
},
multiple: false
});
mediaUploader.on('select', function () {
attachment = mediaUploader.state().get('selection').first().toJSON();
$('#preview-fav, #preview-grav, #preview-thumb').val(attachment.url);
$('.favicon-preview, .gravatar-preview, .thumbnail-preview')
.css('background','url(' + attachment.url + ')');
});
mediaUploader.open();
});
});
</code></pre>
| [
{
"answer_id": 264126,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>This depends on your business model. If your theme is free (or freemium, meaning people can download for free bu... | 2016/12/05 | [
"https://wordpress.stackexchange.com/questions/248367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108354/"
] | I want to call the wordpress media uploader with a button in my theme options page. The thing is that I need three upload media buttons on the same page. I'm trying to do that using jQuery multiple IDs selector. The code is working fine: I click the button and the media uploader is launched, however when I upload anything into the first input field, the media that I just uploaded is passed on to the other input fields in the page. Like they were binded together. Sorry for the stupid question, I dont know much JavaScript. But anyways, how can I fix this??
```
jQuery(document).ready(function( $) {
var mediaUploader;
$('#upload-button-1, #upload-button-2, #upload-button-3').on('click', function(e) {
e.preventDefault();
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Upload',
button: {
text: 'Upload'
},
multiple: false
});
mediaUploader.on('select', function () {
attachment = mediaUploader.state().get('selection').first().toJSON();
$('#preview-fav, #preview-grav, #preview-thumb').val(attachment.url);
$('.favicon-preview, .gravatar-preview, .thumbnail-preview')
.css('background','url(' + attachment.url + ')');
});
mediaUploader.open();
});
});
``` | This depends on your business model. If your theme is free (or freemium, meaning people can download for free but unlock features when they pay you), you should post it into the wordpress.org repository. There's a whole lot of rules you must stick to, which you can [read about here](https://developer.wordpress.org/themes/). The upside of being in the repository is that they will take care of pushing notifications to your users once new versions are available.
If you want to run your own update server, you're up to quite some work, because the WP installations of your users will not simply grant access to a third party computer trying to change files. Your theme must include an API that makes regular calls to your server to see if there is an update, notify the user, download the new theme files and then unpack them to the right directory. It's beyond the scope of WPSE's Q&A model to outline how this sizeable work is done, so you'll have to look for a tutorial ([example](https://code.tutsplus.com/tutorials/a-guide-to-the-wordpress-http-api-automatic-plugin-updates--wp-25181)).
**Note**: do not take for granted that all your users will automatically receive the new version, because [they may have disabled updates](https://codex.wordpress.org/Configuring_Automatic_Background_Updates#Plugin_.26_Theme_Updates_via_Filter). |
248,392 | <p>So basically, what I'm trying to do is to hook a static method of a class to another static method of that same class.</p>
<p>Code is here :</p>
<pre><code>class LocatorMap {
public static function init() {
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'register_scripts' ) );
}
/* add_action( 'wp_enqueue_script', array( 'LocatorMap', 'register_scripts' ) ); */
public function register_scripts() {
global $post;
/* http or https */
$scheme = parse_url( get_bloginfo('url'), PHP_URL_SCHEME );
/* register gmaps api and info box */
wp_register_script( 'google-maps-api', $scheme . '://maps.googleapis.com/maps/api/js', array('jquery'), FALSE, true );
wp_register_script( 'google-maps-info-box', $scheme . '://cdn.rawgit.com/googlemaps/v3-utility-library/infobox/1.1.13/src/infobox.js', array( 'jquery', 'google-maps-api' ), '1.1.13', true );
}
}
</code></pre>
<p>Is this possible? I don't know since I'm a bit new on this kind of a structure.</p>
<p><strong>UPDATE</strong>
I am also calling this class on an external file.</p>
<pre><code>define( DEALERSHIP_MAP_URL, untrailingslashit( plugin_dir_url( __FILE__ ) ) );
define( DEALERSHIP_MAP_DIR, untrailingslashit( plugin_dir_path( __FILE__ ) ) );
define( DEALERSHIP_MAP_TEMPLATE, DEALERSHIP_MAP_DIR . '/templates' );
require_once( 'core/class-locator-map.php' );
register_activation_hook( __FILE__, array( 'LocatorMap', 'init' ) );
</code></pre>
| [
{
"answer_id": 248414,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 5,
"selected": true,
"text": "<p><code>register_activation_hook</code> only runs once i.e. when the plugin is first activated - use the <co... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248392",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58147/"
] | So basically, what I'm trying to do is to hook a static method of a class to another static method of that same class.
Code is here :
```
class LocatorMap {
public static function init() {
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'register_scripts' ) );
}
/* add_action( 'wp_enqueue_script', array( 'LocatorMap', 'register_scripts' ) ); */
public function register_scripts() {
global $post;
/* http or https */
$scheme = parse_url( get_bloginfo('url'), PHP_URL_SCHEME );
/* register gmaps api and info box */
wp_register_script( 'google-maps-api', $scheme . '://maps.googleapis.com/maps/api/js', array('jquery'), FALSE, true );
wp_register_script( 'google-maps-info-box', $scheme . '://cdn.rawgit.com/googlemaps/v3-utility-library/infobox/1.1.13/src/infobox.js', array( 'jquery', 'google-maps-api' ), '1.1.13', true );
}
}
```
Is this possible? I don't know since I'm a bit new on this kind of a structure.
**UPDATE**
I am also calling this class on an external file.
```
define( DEALERSHIP_MAP_URL, untrailingslashit( plugin_dir_url( __FILE__ ) ) );
define( DEALERSHIP_MAP_DIR, untrailingslashit( plugin_dir_path( __FILE__ ) ) );
define( DEALERSHIP_MAP_TEMPLATE, DEALERSHIP_MAP_DIR . '/templates' );
require_once( 'core/class-locator-map.php' );
register_activation_hook( __FILE__, array( 'LocatorMap', 'init' ) );
``` | `register_activation_hook` only runs once i.e. when the plugin is first activated - use the `init` hook instead to "boot up" your plugin:
```
add_action( 'init', 'LocatorMap::init' );
``` |
248,405 | <p>I want to replace the dashes before the page title in the dashboard page list. For each hierarchy below the first, a dash is prepended (as seen in the screenshot below):</p>
<p><a href="https://i.stack.imgur.com/QQUCY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QQUCY.png" alt="enter image description here"></a></p>
<p>It seems that the filter <code>the_title</code> does not affect these dashes:</p>
<pre><code>add_filter( 'the_title', 'change_my_title' );
function change_my_title( $title ) {
return str_replace( '–', $title );
// nor preg_replace or &ndash; or &mdash; work
}
</code></pre>
<p><strong>So my question is:</strong> How can I replace these dashes with something specific? Do I really have to implement a custom list table or meddle around with jQuery? </p>
| [
{
"answer_id": 248407,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>This is <a href=\"https://github.com/WordPress/WordPress/blob/88a72182ca1129f76c1abbf84725d0d01ddad93a/wp-admin/inclu... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40821/"
] | I want to replace the dashes before the page title in the dashboard page list. For each hierarchy below the first, a dash is prepended (as seen in the screenshot below):
[](https://i.stack.imgur.com/QQUCY.png)
It seems that the filter `the_title` does not affect these dashes:
```
add_filter( 'the_title', 'change_my_title' );
function change_my_title( $title ) {
return str_replace( '–', $title );
// nor preg_replace or – or — work
}
```
**So my question is:** How can I replace these dashes with something specific? Do I really have to implement a custom list table or meddle around with jQuery? | You can't change dashes using any filter because there is no filter available to change it.
but still you can change this using jQuery put this code inside functions.php
```
add_action('admin_head',function(){
global $pagenow;
// check current page.
if( $pagenow == 'edit.php' ){ ?>
<script>
jQuery(function($){
var post_title = $('.wp-list-table').find('a.row-title');
$.each(post_title,function(index,em){
var text = $(em).html();
// Replace all dashes to *
$(em).html(text.replace(/—/g ,'*'));
});
});
</script>
<?php
}
});
```
See <https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/class-wp-posts-list-table.php#L918-L919> |
248,416 | <p>I have a problem with WordPress widgets. I want to create a widget like in the images. I know how to create a widget but I don't know query and show the results as in the image.</p>
<p>Explain: We get 10 posts from a category, then show it as title 1 is the first post we get, then Title from 2-10 as in the images. </p>
<p>Could you please help me? </p>
<p><a href="https://i.stack.imgur.com/q8Ewl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q8Ewl.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 248439,
"author": "Den Pat",
"author_id": 103569,
"author_profile": "https://wordpress.stackexchange.com/users/103569",
"pm_score": 0,
"selected": false,
"text": "<p>as bravokeyl told , just try place counter and see if value is 1 , assign some special class and than add s... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108391/"
] | I have a problem with WordPress widgets. I want to create a widget like in the images. I know how to create a widget but I don't know query and show the results as in the image.
Explain: We get 10 posts from a category, then show it as title 1 is the first post we get, then Title from 2-10 as in the images.
Could you please help me?
[](https://i.stack.imgur.com/q8Ewl.png) | Your question is a little short on detail, but let's suppose you have retrieved the posts using [`wp_query`](https://codex.wordpress.org/Class_Reference/WP_Query) and are looping through it like this:
```
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
STUFF
}
wp_reset_postdata();
}
```
In the position of STUFF you want to distinguish between the first post and other posts in which elements you want to retrieve. You can do this by accessing `$current_post`, which holds the number of the post inside the loop. You would get this:
```
if ($the_query->current_post == 0) {
// retrieve featured image, title and content }
else {
// retrieve title only }
``` |
248,419 | <p>I have this action in my plugin page.</p>
<pre><code>add_action ( 'init', 'myStartSession', 1 );
function join_action() {
$a = 1;
include "includes/join.php";
}
add_action ( 'admin_post_nopriv_join', 'join_action' );
add_action ( 'admin_post_join', 'join_action' );
</code></pre>
<p>and I call this from my angularjs app as follows: </p>
<pre><code>$scope.join = function() {
$scope.formData.action = "join";
$http(
{
method : 'POST',
url : '<?php echo MEMBERSHIP_APP; ?>',
data : jQuery.param($scope.formData), // pass in data as strings
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
})
.success(
function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
</code></pre>
<p>where MEMBERSHIP_APP points to wp-admin/admin-ajax.php</p>
<p>Please can you see what I am doing wrong. I have used this construct many times before.</p>
| [
{
"answer_id": 248439,
"author": "Den Pat",
"author_id": 103569,
"author_profile": "https://wordpress.stackexchange.com/users/103569",
"pm_score": 0,
"selected": false,
"text": "<p>as bravokeyl told , just try place counter and see if value is 1 , assign some special class and than add s... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248419",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108395/"
] | I have this action in my plugin page.
```
add_action ( 'init', 'myStartSession', 1 );
function join_action() {
$a = 1;
include "includes/join.php";
}
add_action ( 'admin_post_nopriv_join', 'join_action' );
add_action ( 'admin_post_join', 'join_action' );
```
and I call this from my angularjs app as follows:
```
$scope.join = function() {
$scope.formData.action = "join";
$http(
{
method : 'POST',
url : '<?php echo MEMBERSHIP_APP; ?>',
data : jQuery.param($scope.formData), // pass in data as strings
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
})
.success(
function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
```
where MEMBERSHIP\_APP points to wp-admin/admin-ajax.php
Please can you see what I am doing wrong. I have used this construct many times before. | Your question is a little short on detail, but let's suppose you have retrieved the posts using [`wp_query`](https://codex.wordpress.org/Class_Reference/WP_Query) and are looping through it like this:
```
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
STUFF
}
wp_reset_postdata();
}
```
In the position of STUFF you want to distinguish between the first post and other posts in which elements you want to retrieve. You can do this by accessing `$current_post`, which holds the number of the post inside the loop. You would get this:
```
if ($the_query->current_post == 0) {
// retrieve featured image, title and content }
else {
// retrieve title only }
``` |
248,455 | <p>I'm currently running Wordpress on version <strong>4.6.1</strong> and I'm attempting to search for posts that contains the character <code>-</code> (hyphen). However, the search parameter is taking my hyphen for a negation.</p>
<p>From the <a href="https://codex.wordpress.org/Class_Reference/WP_Query" rel="noreferrer">WP_Query</a> documentation:</p>
<blockquote>
<p>Prepending a term with a hyphen will exclude posts matching that term. Eg, 'pillow -sofa' will return posts containing 'pillow' but not 'sofa' (available since Version 4.4).</p>
</blockquote>
<p>Here's my query:</p>
<pre><code>$query = new WP_Query(array(
'post_type' => array('product', 'product_variation'),
's' => '-',
'posts_per_page' => 36
));
</code></pre>
<p>I've tried to escape the hyphen by doing:</p>
<pre><code>'s' => '\-'
</code></pre>
<p>However, the result stays the same (<code>var_dump($query->request)</code>):</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE
1=1
AND (((wp_posts.post_title NOT LIKE '%%')
AND (wp_posts.post_excerpt NOT LIKE '%%')
AND (wp_posts.post_content NOT LIKE '%%')))
AND (wp_posts.post_password = '')
AND wp_posts.post_type IN ('product', 'product_variation')
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled')
ORDER BY
wp_posts.post_date DESC
LIMIT 0, 36
</code></pre>
| [
{
"answer_id": 248558,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the fact that <code>NOT LIKE '%%'</code> is very unique. It can happen only in cases where you sea... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248455",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104711/"
] | I'm currently running Wordpress on version **4.6.1** and I'm attempting to search for posts that contains the character `-` (hyphen). However, the search parameter is taking my hyphen for a negation.
From the [WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query) documentation:
>
> Prepending a term with a hyphen will exclude posts matching that term. Eg, 'pillow -sofa' will return posts containing 'pillow' but not 'sofa' (available since Version 4.4).
>
>
>
Here's my query:
```
$query = new WP_Query(array(
'post_type' => array('product', 'product_variation'),
's' => '-',
'posts_per_page' => 36
));
```
I've tried to escape the hyphen by doing:
```
's' => '\-'
```
However, the result stays the same (`var_dump($query->request)`):
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE
1=1
AND (((wp_posts.post_title NOT LIKE '%%')
AND (wp_posts.post_excerpt NOT LIKE '%%')
AND (wp_posts.post_content NOT LIKE '%%')))
AND (wp_posts.post_password = '')
AND wp_posts.post_type IN ('product', 'product_variation')
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled')
ORDER BY
wp_posts.post_date DESC
LIMIT 0, 36
``` | One approach is to modify the *exclusion prefix* through the [`wp_query_search_exclusion_prefix`](https://developer.wordpress.org/reference/hooks/wp_query_search_exclusion_prefix/) filter that's supported in WP 4.7+.
See ticket [#38099](https://core.trac.wordpress.org/ticket/38099).
Here's an example how we can change it from `-` to e.g. `!`:
```
add_filter( 'wp_query_search_exclusion_prefix', function( $prefix )
{
return '!'; // adjust to your needs (default is -)
} );
```
where we would use `!apple` instead of `-apple` to exclude `apple` from the search results. Then you can search by `-`.
It looks like the exclusion prefix must be a single character (or empty to disable this feature), because of this [check in the core](https://github.com/WordPress/WordPress/blob/16371b99d8e5111dcc83b8961b4d68681e82d25e/wp-includes/class-wp-query.php#L1335-L1344):
```
// If there is an $exclusion_prefix, terms prefixed with it should be excluded.
$exclude = $exclusion_prefix && ( $exclusion_prefix === substr( $term, 0, 1 ) );
if ( $exclude ) {
$like_op = 'NOT LIKE';
$andor_op = 'AND';
$term = substr( $term, 1 );
} else {
$like_op = 'LIKE';
$andor_op = 'OR';
}
```
Otherwise it sounds like a **bug**, not to be able to search only for the term exclusion prefix.
I wonder if it would be better to add an extra `$exclusion_prefix !== $term` check to support that:
```
$exclude = $exclusion_prefix
&& $exclusion_prefix !== $term
&& ( $exclusion_prefix === mb_substr( $term, 0, 1 ) );
if ( $exclude ) {
$like_op = 'NOT LIKE';
$andor_op = 'AND';
$term = mb_substr( $term, 1 );
} else {
$like_op = 'LIKE';
$andor_op = 'OR';
}
```
where we would also use `mb_substr()` instead of `substr()` for a wider char support for the exclusion prefix.
I guess I should just create ticket for this ... |
248,462 | <p>I have yet to find a concise, start to finish description of how to create a multilingual WordPress theme.</p>
<p>I am a fairly competent developer and have made a few custom themes in my time. For a project I am working on, I am just starting the process of converting my wireframes into WordPress. I already know that this site will only use this one custom theme I am creating, and I know the site will be available in approximately 5 different languages.</p>
<p>There will be a language selector at the top of the page where the user can simply click the flag of their country and it will refresh some internal setting that will change the language of the whole site. From what I understand, you can use po/mo files to translate sites but I can't get my head around it unfortunately.</p>
<p>The ideal scenario would be for me to develop the theme in English, and for any string that will have multiple translations use some localisation function ( __() & _e() ? ). When development is finished, I need to be able to add a translation to each of the translatable strings for each language. I'm fairly sure the solution is to use POEdit but I can't understand how it all links together.</p>
<p>For clarification, I'm not looking for a plugin where you have different translations for different pages/posts. I'm looking for a solution that lets me translate individual strings within my custom theme.</p>
<p>Thanks in advance to any advice you can give.</p>
| [
{
"answer_id": 248466,
"author": "Daniel Mulder",
"author_id": 86859,
"author_profile": "https://wordpress.stackexchange.com/users/86859",
"pm_score": 2,
"selected": false,
"text": "<p>Myself I have done it a few times in recent year but then only for plug-ins that I made. But I think it... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104663/"
] | I have yet to find a concise, start to finish description of how to create a multilingual WordPress theme.
I am a fairly competent developer and have made a few custom themes in my time. For a project I am working on, I am just starting the process of converting my wireframes into WordPress. I already know that this site will only use this one custom theme I am creating, and I know the site will be available in approximately 5 different languages.
There will be a language selector at the top of the page where the user can simply click the flag of their country and it will refresh some internal setting that will change the language of the whole site. From what I understand, you can use po/mo files to translate sites but I can't get my head around it unfortunately.
The ideal scenario would be for me to develop the theme in English, and for any string that will have multiple translations use some localisation function ( \_\_() & \_e() ? ). When development is finished, I need to be able to add a translation to each of the translatable strings for each language. I'm fairly sure the solution is to use POEdit but I can't understand how it all links together.
For clarification, I'm not looking for a plugin where you have different translations for different pages/posts. I'm looking for a solution that lets me translate individual strings within my custom theme.
Thanks in advance to any advice you can give. | Daniel's answer was very similar, but applied to plugins rather than themes. For that reason I'll explain how I specifically did it for themes for anyone else who comes across this problem.
1. Create a folder in the root of your theme called "languages"
2. Go to <https://wpcentral.io/internationalization/>, search for your language and copy the "WordPress Locale" code (e.g. cs\_CZ for Czech)
3. Open Poedit
4. File -> New
5. Paste the code you coped from wpcentral into the box that appears
6. Press save, and save to the "languages" folder you created in step 1
7. Press "Extract from sources" (or Catalogue->Properties)
8. Under "Sources Paths" press the + on the Paths box
9. Select your theme folder (e.g. wp-content/themes/my-theme)
10. In the "Sources Keywords" tab, press "New Item"
11. Type "\_\_" (underscore underscore, no quotes), and press enter
12. Type "\_e" (no quotes), and press enter
13. Press OK
14. Press Save
15. Press Catalogue->Update from sources
16. You should see all translatable strings from your theme appear (basically any time you use "\_\_( 'Hello world', 'mydomain' )", the translation will appear)
17. Once you have completed your translations, press File->Compile to MO (save in the same languages folder from step 1)
18. Add the following code to the top of your theme's functions file:
```
function mytheme_localisation(){
function mytheme_localised( $locale ) {
if ( isset( $_GET['l'] ) ) {
return sanitize_key( $_GET['l'] );
}
return $locale;
}
add_filter( 'locale', 'mytheme_localised' );
load_theme_textdomain( 'mytheme', get_template_directory() . '/languages' );
}
add_action( 'after_setup_theme', 'mytheme_localisation' );
```
19. Now to dynamically translate your site, you can simply add the URL parameter l={language code} (e.g. mysite.com/?l=cs\_CZ - this will load the cs\_CZ.mo file that we translated using poedit)
To summarise: to translate strings within your theme, use the following code:
```
__( 'Hello, World!', 'mytheme' )
```
Where 'mytheme' is the textdomain you set in the function from step 18. Combine this with the creation of the PO/MO files using Poedit and you will be able to make your theme multilingual. In my case this was the perfect solution as I can dynamically change the language using a flag selector on my site, and I can store the user's preference in a cookie, and redirect them when they arrive back.
I hope this helps someone else who has a similar problem, as this took me *ages* to figure out. |
248,464 | <p>What is the best way to pass/get data to/from the <code>data-product_variations</code> attr form in Product Single pages. I am working on some interactions with the product gallery images and the product variations, all of these while using WooCommerce.</p>
<p>Basically, I need to be able to trigger some stuff on the <code>woocommerce_variation_has_changed</code> event.</p>
<p>I have been able to pass and get my data attributes while hooking to <code>single_product_large_thumbnail_size</code> and <code>woocommerce_single_product_image_thumbnail_html</code>.</p>
<p>I have <strong>not</strong> been able to pass/get that data during the <code>woocommerce_variation_has_changed</code> event. What I have understood (?) is that the <code>woocommerce_variation_has_changed</code> trigger gets its data from the <code>data-product_variations</code> object to insert the product variation related image markup.</p>
<p>Summing it up, how would I go to add data attr’s to the <code>data-product_variations</code> object? And what would be the best way to get that data during the <code>woocommerce_variation_has_changed</code> event?</p>
<p>This is how the object inside the <code>data-product_variations</code> looks like.
Basically I need to be able to pass a <code>data-attr</code> to the featured image tag when <code>woocommerce_variation_has_changed</code> kicks in.</p>
<pre><code>data-product_variations="[{
"variation_id": 373,
"variation_is_visible": true,
"variation_is_active": true,
"is_purchasable": true,
"display_price": 100,
"display_regular_price": 100,
"attributes": {
"attribute_pa_chain-length": "80cm"
},
"image_src": "",
"image_link": "",
"image_title": "",
"image_alt": "",
"image_caption": "",
"image_srcset": "",
"image_sizes": "",
"price_html": "<span class=\"price\"><span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">&pound;<\/span>100.00<\/span><\/span>",
"availability_html": "",
"sku": "",
"weight": " kg",
"dimensions": "",
"min_qty": 1,
"max_qty": null,
"backorders_allowed": false,
"is_in_stock": true,
"is_downloadable": false,
"is_virtual": false,
"is_sold_individually": "no",
"variation_description": ""
}]"
</code></pre>
| [
{
"answer_id": 368161,
"author": "Michael Aro",
"author_id": 189311,
"author_profile": "https://wordpress.stackexchange.com/users/189311",
"pm_score": 1,
"selected": false,
"text": "<pre><code> jQuery(document).on('found_variation.wc-variation-form', 'form.variations_form', function(eve... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248464",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35530/"
] | What is the best way to pass/get data to/from the `data-product_variations` attr form in Product Single pages. I am working on some interactions with the product gallery images and the product variations, all of these while using WooCommerce.
Basically, I need to be able to trigger some stuff on the `woocommerce_variation_has_changed` event.
I have been able to pass and get my data attributes while hooking to `single_product_large_thumbnail_size` and `woocommerce_single_product_image_thumbnail_html`.
I have **not** been able to pass/get that data during the `woocommerce_variation_has_changed` event. What I have understood (?) is that the `woocommerce_variation_has_changed` trigger gets its data from the `data-product_variations` object to insert the product variation related image markup.
Summing it up, how would I go to add data attr’s to the `data-product_variations` object? And what would be the best way to get that data during the `woocommerce_variation_has_changed` event?
This is how the object inside the `data-product_variations` looks like.
Basically I need to be able to pass a `data-attr` to the featured image tag when `woocommerce_variation_has_changed` kicks in.
```
data-product_variations="[{
"variation_id": 373,
"variation_is_visible": true,
"variation_is_active": true,
"is_purchasable": true,
"display_price": 100,
"display_regular_price": 100,
"attributes": {
"attribute_pa_chain-length": "80cm"
},
"image_src": "",
"image_link": "",
"image_title": "",
"image_alt": "",
"image_caption": "",
"image_srcset": "",
"image_sizes": "",
"price_html": "<span class=\"price\"><span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">£<\/span>100.00<\/span><\/span>",
"availability_html": "",
"sku": "",
"weight": " kg",
"dimensions": "",
"min_qty": 1,
"max_qty": null,
"backorders_allowed": false,
"is_in_stock": true,
"is_downloadable": false,
"is_virtual": false,
"is_sold_individually": "no",
"variation_description": ""
}]"
``` | ```
jQuery(document).on('found_variation.wc-variation-form', 'form.variations_form', function(event, variation_data) {
//this is called when a valid productis found
});
jQuery(document).on('change.wc-variation-form', 'form.variations_form', function(event) {
//this function is called when the user clicks or changes the dropdown
});
```
The PHP function you are looking for is
```
apply_filters(
'woocommerce_available_variation',
array(
'attributes' => $variation->get_variation_attributes(),
'availability_html' => wc_get_stock_html( $variation ),
'backorders_allowed' => $variation->backorders_allowed(),
'dimensions' => $variation->get_dimensions( false ),
'dimensions_html' => wc_format_dimensions( $variation->get_dimensions( false ) ),
'display_price' => wc_get_price_to_display( $variation ),
'display_regular_price' => wc_get_price_to_display( $variation, array( 'price' => $variation->get_regular_price() ) ),
'image' => wc_get_product_attachment_props( $variation->get_image_id() ),
'image_id' => $variation->get_image_id(),
'is_downloadable' => $variation->is_downloadable(),
'is_in_stock' => $variation->is_in_stock(),
'is_purchasable' => $variation->is_purchasable(),
'is_sold_individually' => $variation->is_sold_individually() ? 'yes' : 'no',
'is_virtual' => $variation->is_virtual(),
'max_qty' => 0 < $variation->get_max_purchase_quantity() ? $variation->get_max_purchase_quantity() : '',
'min_qty' => $variation->get_min_purchase_quantity(),
'price_html' => $show_variation_price ? '<span class="price">' . $variation->get_price_html() . '</span>' : '',
'sku' => $variation->get_sku(),
'variation_description' => wc_format_content( $variation->get_description() ),
'variation_id' => $variation->get_id(),
'variation_is_active' => $variation->variation_is_active(),
'variation_is_visible' => $variation->variation_is_visible(),
'weight' => $variation->get_weight(),
'weight_html' => wc_format_weight( $variation->get_weight() ),
),
$this,
$variation
);
```
This is found here <https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-product-variable.php#L325>
```
WC_Product_Variable -> get_available_variation( $variation )
``` |
248,480 | <p>Is there a filter available that would let you specify that a module is active, without you having to use the admin area? I've found filters that let you <em>hide</em> modules, but so far nothing for <em>activating</em> modules.</p>
<p>Essentially, I want to be able to define it as <em>always on</em> so that A) a client can't accidentally disable it, B) it saves me from having to sync DB settings across different environments.</p>
| [
{
"answer_id": 248483,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Third party plugins (yeah, including jetpack) are off topic on WPSE, but well, here you go: Jetpack has a filter... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248480",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60767/"
] | Is there a filter available that would let you specify that a module is active, without you having to use the admin area? I've found filters that let you *hide* modules, but so far nothing for *activating* modules.
Essentially, I want to be able to define it as *always on* so that A) a client can't accidentally disable it, B) it saves me from having to sync DB settings across different environments. | Third party plugins (yeah, including jetpack) are off topic on WPSE, but well, here you go: Jetpack has a filter [`jetpack_get_available_modules`](https://developer.jetpack.com/hooks/jetpack_get_available_modules/), which lets you edit the array of active modules. You can disable a module by unsetting it from the array, or enable it by adding it. Here's how to enable a single module, 'sharedaddy':
```
function wpse248480_filter_jetpack( $modules, $min_version, $max_version ) {
if (!(in_array('sharedaddy',$modules))) $modules[] = 'sharedaddy';
return $modules;
}
add_filter( 'jetpack_get_available_modules', 'wpse248480_filter_jetpack', 20, 3 );
```
**UPDATE**
The above only filters the available modules. To actually (de)activate them programmatically use ([source](https://github.com/Automattic/jetpack/blob/master/class.jetpack.php#L2478)):
```
function wpse248480_activate_jetpack () {
Jetpack::activate_module('sharedaddy');
// Jetpack::deactivate_module('sharedaddy');
}
add_action('after_setup_theme','wpse248480_activate_jetpack');
``` |
248,489 | <p>I have a particular issue. I have only 2 roles on my site, admin and a secondary role used for various administrative tasks in the backend. </p>
<p>This secondary role needs to normally redirect to a frontend page when they login, UNLESS the redirect_to URL parameter is set while they're logging in. </p>
<p>I have tried using login_redirect, but to no avail. Here is what I currently have:</p>
<pre><code>function redirect_users_by_role() {
if ( ! defined( 'DOING_AJAX' ) ) {
$current_user = wp_get_current_user();
$role_name = $current_user->roles[0];
$admin_url = home_url().'/wp-admin/';
if ( 'subscriber' === $role_name ) {
wp_safe_redirect( home_url('/access-denied') );
}
if (empty($role_name)) {
wp_safe_redirect( home_url('/access-denied') );
}
if ( 'staff' === $role_name && isset($_REQUEST['redirect_to']) && !empty($_REQUEST['redirect_to']) ) {
wp_safe_redirect( $_REQUEST['redirect_to'] );
}
elseif ( 'staff' === $role_name && $_REQUEST['redirect_to'] == $admin_url ) {
wp_safe_redirect( home_url('/resources')); exit;
}
} // DOING_AJAX
} // redirect_users_by_role
add_action( 'admin_init', 'redirect_users_by_role' );
</code></pre>
<p>If a user with a role of staff logs in and redirect_to is empty when the login_redirect POSTs to itself, then they should go to home_url().'/resources', otherwise, if they're logging in with the role of staff but redirect_to IS set, then they should be redirected to that. I have been completely unable to figure this out. Any help is greatly appreciated.</p>
<p><strong>UPDATE</strong></p>
<p>Here is what I ultimately ended up doing to get this to work. Since this is a very specific instance in my user flow, I doubt it will be helpful to anyone, but I wanted to make sure I added the working solution, anyway.</p>
<pre><code>function admin_login_redirect( $url, $request, $user ){
//is there a user
if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
//is user admin
if( $user->has_cap( 'administrator' ) ) {
//go do admin stuff
$url = admin_url();
//but wait there's more
}
}
return $url;
}
add_filter('login_redirect', 'admin_login_redirect', 10, 3 );
function staff_login_redirect( $url, $request, $user ){
if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
if( $user->has_cap('staff') && strpos($_REQUEST['redirect_to'], 'gf_entries') == false ) {
//please god work
$url = home_url() . '/resources';
//but waittt there's more
} else {
//damnit all
if( $user->has_cap('staff') && isset($_REQUEST['redirect_to']) && strpos($_REQUEST['redirect_to'], 'gf_entries') !== false) {
$url = $_REQUEST['redirect_to'];
}
}
}
return $url;
}
add_filter('login_redirect', 'staff_login_redirect', 10, 3 );
function transient_login_redirect( $url, $request, $user ) {
if ( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
if (!$user->has_cap('administrator') && !$user->has_cap('staff') ) {
//go away
$url= home_url('/access-denied');
}
}
return $url;
}
add_filter('login_redirect', 'transient_login_redirect', 10, 3);
</code></pre>
<p>The final solution was to check for several things, on top of splitting up the logic into different functions and hook into the login_redirect hook.</p>
<p>For admins, I just send them wherever. </p>
<p>For staff, I check if they're going to the one place in the backend where they should be on any given day, gravity forms page 'gf_entries', using strpos(). If they're not headed to that area of wp-admin via the $_REQUEST['redirect_to'] parameter, then we send them over to /resources (my internal page for staff resources).</p>
<p>Thanks for your help everyone!</p>
| [
{
"answer_id": 248507,
"author": "pixeline",
"author_id": 82,
"author_profile": "https://wordpress.stackexchange.com/users/82",
"pm_score": 2,
"selected": false,
"text": "<p>The login_redirect hook does seem to be the right hook.</p>\n\n<p>Can you try this :</p>\n\n<p>(Adapted from the <... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/72933/"
] | I have a particular issue. I have only 2 roles on my site, admin and a secondary role used for various administrative tasks in the backend.
This secondary role needs to normally redirect to a frontend page when they login, UNLESS the redirect\_to URL parameter is set while they're logging in.
I have tried using login\_redirect, but to no avail. Here is what I currently have:
```
function redirect_users_by_role() {
if ( ! defined( 'DOING_AJAX' ) ) {
$current_user = wp_get_current_user();
$role_name = $current_user->roles[0];
$admin_url = home_url().'/wp-admin/';
if ( 'subscriber' === $role_name ) {
wp_safe_redirect( home_url('/access-denied') );
}
if (empty($role_name)) {
wp_safe_redirect( home_url('/access-denied') );
}
if ( 'staff' === $role_name && isset($_REQUEST['redirect_to']) && !empty($_REQUEST['redirect_to']) ) {
wp_safe_redirect( $_REQUEST['redirect_to'] );
}
elseif ( 'staff' === $role_name && $_REQUEST['redirect_to'] == $admin_url ) {
wp_safe_redirect( home_url('/resources')); exit;
}
} // DOING_AJAX
} // redirect_users_by_role
add_action( 'admin_init', 'redirect_users_by_role' );
```
If a user with a role of staff logs in and redirect\_to is empty when the login\_redirect POSTs to itself, then they should go to home\_url().'/resources', otherwise, if they're logging in with the role of staff but redirect\_to IS set, then they should be redirected to that. I have been completely unable to figure this out. Any help is greatly appreciated.
**UPDATE**
Here is what I ultimately ended up doing to get this to work. Since this is a very specific instance in my user flow, I doubt it will be helpful to anyone, but I wanted to make sure I added the working solution, anyway.
```
function admin_login_redirect( $url, $request, $user ){
//is there a user
if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
//is user admin
if( $user->has_cap( 'administrator' ) ) {
//go do admin stuff
$url = admin_url();
//but wait there's more
}
}
return $url;
}
add_filter('login_redirect', 'admin_login_redirect', 10, 3 );
function staff_login_redirect( $url, $request, $user ){
if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
if( $user->has_cap('staff') && strpos($_REQUEST['redirect_to'], 'gf_entries') == false ) {
//please god work
$url = home_url() . '/resources';
//but waittt there's more
} else {
//damnit all
if( $user->has_cap('staff') && isset($_REQUEST['redirect_to']) && strpos($_REQUEST['redirect_to'], 'gf_entries') !== false) {
$url = $_REQUEST['redirect_to'];
}
}
}
return $url;
}
add_filter('login_redirect', 'staff_login_redirect', 10, 3 );
function transient_login_redirect( $url, $request, $user ) {
if ( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
if (!$user->has_cap('administrator') && !$user->has_cap('staff') ) {
//go away
$url= home_url('/access-denied');
}
}
return $url;
}
add_filter('login_redirect', 'transient_login_redirect', 10, 3);
```
The final solution was to check for several things, on top of splitting up the logic into different functions and hook into the login\_redirect hook.
For admins, I just send them wherever.
For staff, I check if they're going to the one place in the backend where they should be on any given day, gravity forms page 'gf\_entries', using strpos(). If they're not headed to that area of wp-admin via the $\_REQUEST['redirect\_to'] parameter, then we send them over to /resources (my internal page for staff resources).
Thanks for your help everyone! | The login\_redirect hook does seem to be the right hook.
Can you try this :
(Adapted from the [Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect) )
```
function redirect_users_by_role( $redirect_to, $request, $user ) {
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
if ( in_array( 'staff', $user->roles ) ) {
if ($admin_url === $request){
return home_url('/resources');
} else{
return $redirect_to;
}
}
} else {
return home_url('/access-denied');
}
}
add_filter( 'login_redirect', 'redirect_users_by_role', 10, 3 );
``` |
248,501 | <p>I am using a currency widget to show live currencies for different countries. I also use W3 Total Cache plugin and the widget data is cached. For example yesterday's prices are shown for today and I have to manually purge all caches to get the new data. </p>
<p>Is there anyway to disable cache for certain widgets? or clear the cache every hour for that widget?</p>
| [
{
"answer_id": 248504,
"author": "pixeline",
"author_id": 82,
"author_profile": "https://wordpress.stackexchange.com/users/82",
"pm_score": 0,
"selected": false,
"text": "<p>The recommended solution is to have your currency widget refresh its data via ajax.</p>\n"
},
{
"answer_id... | 2016/12/06 | [
"https://wordpress.stackexchange.com/questions/248501",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108450/"
] | I am using a currency widget to show live currencies for different countries. I also use W3 Total Cache plugin and the widget data is cached. For example yesterday's prices are shown for today and I have to manually purge all caches to get the new data.
Is there anyway to disable cache for certain widgets? or clear the cache every hour for that widget? | You need to use fragment caching so enable PHP in the widget and then use the following tags:
```
<!-- mfunc -->
```
The following links should help:
<https://wordpress.org/support/topic/using-shortcodes-with-fragment-caching/>
<https://www.justinsilver.com/technology/wordpress/w3-total-cache-fragment-caching-wordpress/> |
248,559 | <p>Is it possible to change the comment-meta fields?</p>
<p>I have tried searching the file structure and cannot see what function is writing it - all I want to do is change the word "says"</p>
<pre><code><ol class="comment-list">
<li id="comment-2" class="comment byuser comment-author-james bypostauthor even thread-even depth-1 parent">
<article id="div-comment-2" class="comment-body">
<footer class="comment-meta">
<div class="comment-author vcard">
<b class="fn">james</b> <span class="says">says:</span> </div><!-- .comment-author -->
<div class="comment-metadata">
</code></pre>
<p>Thanks
James</p>
| [
{
"answer_id": 248522,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of delete, you can move all files from <code>/wp</code> to <code>root</code> folder. </p>\n\n<p>Then use ... | 2016/12/07 | [
"https://wordpress.stackexchange.com/questions/248559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104443/"
] | Is it possible to change the comment-meta fields?
I have tried searching the file structure and cannot see what function is writing it - all I want to do is change the word "says"
```
<ol class="comment-list">
<li id="comment-2" class="comment byuser comment-author-james bypostauthor even thread-even depth-1 parent">
<article id="div-comment-2" class="comment-body">
<footer class="comment-meta">
<div class="comment-author vcard">
<b class="fn">james</b> <span class="says">says:</span> </div><!-- .comment-author -->
<div class="comment-metadata">
```
Thanks
James | Instead of delete, you can move all files from `/wp` to `root` folder.
Then use this script to replace url from `example.com/wp` to `example.com` inside the database <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/>
Follow these few steps.
1. Move all your website files to root from `/wp` folder.
2. Upload the script folder to your web root.
3. Browse to the script file URL in your web browser. eg. <http://example.com/Search-Replace-DB/>
4. Fill in the fields as needed.
5. Hit on run button
It will replace all your old string to your new string inside the database. |
248,567 | <p>How do I display the commentor's first name and last name in the comments?... rather than their username as currently shows.</p>
| [
{
"answer_id": 248591,
"author": "Felipe Rodrigues",
"author_id": 104101,
"author_profile": "https://wordpress.stackexchange.com/users/104101",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at the <code>'callback'</code> argument of the function <code>wp_list_comments</code>.... | 2016/12/07 | [
"https://wordpress.stackexchange.com/questions/248567",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] | How do I display the commentor's first name and last name in the comments?... rather than their username as currently shows. | This will get you a first name + last name combination if available, or just the first name or last name if that's all your user submitted.
This assumes you're interested in registered user's names. If you're going to add first and last names to your commenting form... or treat first + last name as "display name" from the back end forward (so possibly not just in commenting forms), either would be something different!
For theme functions.php or plug-in:
```
add_filter( 'get_comment_author', 'wpse_use_user_real_name', 10, 3 ) ;
//use registered commenter first and/or last names if available
function wpse_use_user_real_name( $author, $comment_id, $comment ) {
$firstname = '' ;
$lastname = '' ;
//returns 0 for unregistered commenters
$user_id = $comment->user_id ;
if ( $user_id ) {
$user_object = get_userdata( $user_id ) ;
$firstname = $user_object->user_firstname ;
$lastname = $user_object->user_lastname ;
}
if ( $firstname || $lastname ) {
$author = $firstname . ' ' . $lastname ;
//remove blank space if one of two names is missing
$author = trim( $author ) ;
}
return $author ;
}
```
Your results may of course vary depending on your installation and whatever particular requirements you may have added 1) for commenting (i.e., "anyone" vs "registered only") and 2) for signing up (are First and Last Name required to register?).
Additionally, in a full installation, you might want to adjust the user profile page, where the user selects a "display name." If you're going to display firstname/lastname instead then it'd be best to deal with that one way or another - by restricting choices, for example, or by adjusting labels and instructions. |
248,570 | <p>I'm having some issues getting the default values set in the WordPress Customizer to save to the database upon initial install without first having the user save the Customizer to set them. I've tried the solution from this thread with no luck:</p>
<p><a href="https://wordpress.stackexchange.com/questions/143789/use-default-value-of-wp-customizer-in-theme-mod-output">Use default value of wp_customizer in theme_mod output?</a></p>
<pre><code>Customizer section/setting/control
//Social Icons Section
$wp_customize->add_section( 'socialsection', array(
'title' => __( 'Social Media' ),
'priority' => 4,
'capability' => 'edit_theme_options',
) );
//Settings & Controls For Social Media
$wp_customize->add_setting( 'facebooklink_edit', array(
'default' => '#',
'sanitize_callback' => 'esc_attr',
'transport' => 'refresh',
) );
$wp_customize->add_control('facebooklink_edit', array(
'label' => __( 'Facebook Link', 'spiffing' ),
'section' => 'socialsection',
) );
</code></pre>
<p>Output on Frontend:</p>
<pre><code><a href="<?php echo get_theme_mod('facebooklink_edit', '#'); ?>"><div class="fb-footer" id="fb-footer-bg"><i class="fa fa-facebook-f"></i></div></a>
</code></pre>
<p>CSS manipulation based on user action in customzier:</p>
<pre><code> ?>
<style type="text/css">
<?php if( get_theme_mod( 'facebooklink_edit' ) == '' ) { ?>
#fb-footer-bg { display: none; }
<?php } // end if ?>
</style>
<?php
</code></pre>
<p>From the above, you can see that this mod just by default sets the value to a '#', and if it then detects that there is no '#' is adds the 'display:none' to that id. Should be simple enough. However, it appears as if the if statement sees that it's condition is met which is this case is blank '' and applies the 'display:none'. but as you can see in both default sections on the frontend and customzier I have set the default to be a '#'. It even writes it into the placeholder section in the customzier, just not the database.</p>
<p>It works if the user AFTER initial install goes into the customizer and clicks 'save'. Maybe initiating a value into the database which is then read and displayed on the frontend.</p>
<p>I've got this to work with links etc, but this mod is different in the sense that it manipulates a div by adding a 'display: none'.</p>
<p>Any ideas appreciated.</p>
| [
{
"answer_id": 248591,
"author": "Felipe Rodrigues",
"author_id": 104101,
"author_profile": "https://wordpress.stackexchange.com/users/104101",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at the <code>'callback'</code> argument of the function <code>wp_list_comments</code>.... | 2016/12/07 | [
"https://wordpress.stackexchange.com/questions/248570",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108509/"
] | I'm having some issues getting the default values set in the WordPress Customizer to save to the database upon initial install without first having the user save the Customizer to set them. I've tried the solution from this thread with no luck:
[Use default value of wp\_customizer in theme\_mod output?](https://wordpress.stackexchange.com/questions/143789/use-default-value-of-wp-customizer-in-theme-mod-output)
```
Customizer section/setting/control
//Social Icons Section
$wp_customize->add_section( 'socialsection', array(
'title' => __( 'Social Media' ),
'priority' => 4,
'capability' => 'edit_theme_options',
) );
//Settings & Controls For Social Media
$wp_customize->add_setting( 'facebooklink_edit', array(
'default' => '#',
'sanitize_callback' => 'esc_attr',
'transport' => 'refresh',
) );
$wp_customize->add_control('facebooklink_edit', array(
'label' => __( 'Facebook Link', 'spiffing' ),
'section' => 'socialsection',
) );
```
Output on Frontend:
```
<a href="<?php echo get_theme_mod('facebooklink_edit', '#'); ?>"><div class="fb-footer" id="fb-footer-bg"><i class="fa fa-facebook-f"></i></div></a>
```
CSS manipulation based on user action in customzier:
```
?>
<style type="text/css">
<?php if( get_theme_mod( 'facebooklink_edit' ) == '' ) { ?>
#fb-footer-bg { display: none; }
<?php } // end if ?>
</style>
<?php
```
From the above, you can see that this mod just by default sets the value to a '#', and if it then detects that there is no '#' is adds the 'display:none' to that id. Should be simple enough. However, it appears as if the if statement sees that it's condition is met which is this case is blank '' and applies the 'display:none'. but as you can see in both default sections on the frontend and customzier I have set the default to be a '#'. It even writes it into the placeholder section in the customzier, just not the database.
It works if the user AFTER initial install goes into the customizer and clicks 'save'. Maybe initiating a value into the database which is then read and displayed on the frontend.
I've got this to work with links etc, but this mod is different in the sense that it manipulates a div by adding a 'display: none'.
Any ideas appreciated. | This will get you a first name + last name combination if available, or just the first name or last name if that's all your user submitted.
This assumes you're interested in registered user's names. If you're going to add first and last names to your commenting form... or treat first + last name as "display name" from the back end forward (so possibly not just in commenting forms), either would be something different!
For theme functions.php or plug-in:
```
add_filter( 'get_comment_author', 'wpse_use_user_real_name', 10, 3 ) ;
//use registered commenter first and/or last names if available
function wpse_use_user_real_name( $author, $comment_id, $comment ) {
$firstname = '' ;
$lastname = '' ;
//returns 0 for unregistered commenters
$user_id = $comment->user_id ;
if ( $user_id ) {
$user_object = get_userdata( $user_id ) ;
$firstname = $user_object->user_firstname ;
$lastname = $user_object->user_lastname ;
}
if ( $firstname || $lastname ) {
$author = $firstname . ' ' . $lastname ;
//remove blank space if one of two names is missing
$author = trim( $author ) ;
}
return $author ;
}
```
Your results may of course vary depending on your installation and whatever particular requirements you may have added 1) for commenting (i.e., "anyone" vs "registered only") and 2) for signing up (are First and Last Name required to register?).
Additionally, in a full installation, you might want to adjust the user profile page, where the user selects a "display name." If you're going to display firstname/lastname instead then it'd be best to deal with that one way or another - by restricting choices, for example, or by adjusting labels and instructions. |
248,618 | <p>I have set up links to the next/previous posts on my <code>single.php</code> template. Currently I am using <code><?php previous_post_link(); ?></code> and <code><?php next_post_link(); ?></code> which gives me the title of the next/previous posts, but I would also like to be able to display the author of those posts below the title. Is this possible?</p>
| [
{
"answer_id": 248620,
"author": "MaximOrlovsky",
"author_id": 15294,
"author_profile": "https://wordpress.stackexchange.com/users/15294",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, you can do that. Change <code><?php previous_post_link(); ?></code> and <code><?php next_p... | 2016/12/07 | [
"https://wordpress.stackexchange.com/questions/248618",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13286/"
] | I have set up links to the next/previous posts on my `single.php` template. Currently I am using `<?php previous_post_link(); ?>` and `<?php next_post_link(); ?>` which gives me the title of the next/previous posts, but I would also like to be able to display the author of those posts below the title. Is this possible? | Yes, you can do that. Change `<?php previous_post_link(); ?>` and `<?php next_post_link(); ?>` with the following code:
For previous post:
```
<?php
$prev_post = get_previous_post();
$prev_user = get_user_by( 'id', $prev_post->post_author );
if (!empty( $prev_post )): ?>
<a href="<?php echo $prev_post->guid ?>"><?php echo $prev_post->post_title ?> (<?php echo $prev_user->first_name . ' ' . $prev_user->last_name; ?>)</a>
<?php endif ?>
```
For next post:
```
<?php
$next_post = get_next_post();
$next_user = get_user_by( 'id', $next_post->post_author );
if (!empty( $prev_post )): ?>
<a href="<?php echo $next_post->guid ?>"><?php echo $next_post->post_title ?> (<?php echo $next_user->first_name . ' ' . $next_user->last_name; ?>)</a>
<?php endif ?>
```
You also can control from which categories WordPress should select previous and next posts. `get_previous_post` and `get_next_post` accept two parameters:
* `(bool) $in_same_cat` — prev/next posts will be selected from the same category as you current post
* `(string) $excluded_categories` — posts related to these categories will be skipped
More details about these parameters you may [find here](https://codex.wordpress.org/Function_Reference/get_previous_post) |
248,621 | <p>I just upgraded to WP 4.7, and suddenly code that uses get_post_type($id) stopped returning anything, and didn't throw an error either.</p>
<p>After trying a few things, I found that it would start working again if I changed my code from </p>
<pre><code>get_post_type($id)
</code></pre>
<p>to</p>
<pre><code>get_post_type(intval($id))
</code></pre>
<p>But I can't find anything in the docs about WP suddenly requiring explicit integer values. Anyone else seeing this?</p>
<p><strong>UPDATE</strong></p>
<p>So, using trim instead of intval works too. </p>
<pre><code>get_post_type(trim($id))
</code></pre>
<p>And checking $id <code>(preg_match('/\s/',$id))</code> shows that it had a space. But oddly, this worked just fine in WP 4.6, so something must have changed to make that less forgiving in WP 4.7</p>
| [
{
"answer_id": 248627,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I can tell this is untrue. Let's fall down the rabbit hole...</p>\n\n<p>First we call <a href=\"h... | 2016/12/07 | [
"https://wordpress.stackexchange.com/questions/248621",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11023/"
] | I just upgraded to WP 4.7, and suddenly code that uses get\_post\_type($id) stopped returning anything, and didn't throw an error either.
After trying a few things, I found that it would start working again if I changed my code from
```
get_post_type($id)
```
to
```
get_post_type(intval($id))
```
But I can't find anything in the docs about WP suddenly requiring explicit integer values. Anyone else seeing this?
**UPDATE**
So, using trim instead of intval works too.
```
get_post_type(trim($id))
```
And checking $id `(preg_match('/\s/',$id))` shows that it had a space. But oddly, this worked just fine in WP 4.6, so something must have changed to make that less forgiving in WP 4.7 | According to the devs at WP (<https://core.trac.wordpress.org/ticket/39164>):
"This was an intentional change to get\_post() in 4.7 - passing an invalid parameter may have previously returned a result, but it could've been an incorrect resource, for example, a value being cast to a numeric 1 and fetching from the incorrect post.
get\_post( 123 ) is the same as get\_post( '123' ) but not the same as get\_post( " 123 " ) (Which now fails) IMHO, so I agree with the change, especially in this case."
So I would consider this the definitive answer. The behavior has changed to something better, it was just a surprise that it worked before. |
248,647 | <p>I have a modal category and in my modal category i have three sub-categories in it. Here is the structure of my modal category.</p>
<pre><code>-Modal
-Water Pumps
-Water Heaters
-Electrical
</code></pre>
<p>Here, i want to only get a post from my water pumps sub-category from my Modal category and to be displayed in my modal. Here is my code where it displays all that has a category name of modal, how can i restrict it to category name modal and sub-category of water pumps</p>
<pre><code><div id="myModal38" class="modal fade" tabindex="-1">
<?php $args1 = array(
'post_type' => 'post',
'category_name' => 'modal',
'posts_per_page' => '1',
);
$modalPost = new WP_Query( $args1 );
if( $modalPost->have_posts() ) :
?>
<div class="modal-dialog">
<?php while ( $modalPost->have_posts() ) : $modalPost->the_post(); ?>
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" data-dismiss="modal">×</button>
<h4 class="modal-title"><?php the_title(); ?></h4>
</div>
<div class="modal-body">
<?php the_post_thumbnail(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal -->
</code></pre>
| [
{
"answer_id": 248627,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I can tell this is untrue. Let's fall down the rabbit hole...</p>\n\n<p>First we call <a href=\"h... | 2016/12/08 | [
"https://wordpress.stackexchange.com/questions/248647",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105020/"
] | I have a modal category and in my modal category i have three sub-categories in it. Here is the structure of my modal category.
```
-Modal
-Water Pumps
-Water Heaters
-Electrical
```
Here, i want to only get a post from my water pumps sub-category from my Modal category and to be displayed in my modal. Here is my code where it displays all that has a category name of modal, how can i restrict it to category name modal and sub-category of water pumps
```
<div id="myModal38" class="modal fade" tabindex="-1">
<?php $args1 = array(
'post_type' => 'post',
'category_name' => 'modal',
'posts_per_page' => '1',
);
$modalPost = new WP_Query( $args1 );
if( $modalPost->have_posts() ) :
?>
<div class="modal-dialog">
<?php while ( $modalPost->have_posts() ) : $modalPost->the_post(); ?>
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" data-dismiss="modal">×</button>
<h4 class="modal-title"><?php the_title(); ?></h4>
</div>
<div class="modal-body">
<?php the_post_thumbnail(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal -->
``` | According to the devs at WP (<https://core.trac.wordpress.org/ticket/39164>):
"This was an intentional change to get\_post() in 4.7 - passing an invalid parameter may have previously returned a result, but it could've been an incorrect resource, for example, a value being cast to a numeric 1 and fetching from the incorrect post.
get\_post( 123 ) is the same as get\_post( '123' ) but not the same as get\_post( " 123 " ) (Which now fails) IMHO, so I agree with the change, especially in this case."
So I would consider this the definitive answer. The behavior has changed to something better, it was just a surprise that it worked before. |
248,701 | <p>I am struggling to make this script working on Wordpress. On Fiddle it works well <a href="https://jsfiddle.net/xqxk2qdg/2/" rel="nofollow noreferrer">https://jsfiddle.net/xqxk2qdg/2/</a> Any idea why could I have this problem? It is properly enqueued and loaded on page.</p>
<pre><code>var array = [];
var array1 = $('#input_8_3').val().split(',');
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
</code></pre>
| [
{
"answer_id": 248713,
"author": "depiction",
"author_id": 101731,
"author_profile": "https://wordpress.stackexchange.com/users/101731",
"pm_score": 2,
"selected": false,
"text": "<p>By default, jQuery runs in no conflict mode in WordPress. You have an anonymous function that passes the ... | 2016/12/08 | [
"https://wordpress.stackexchange.com/questions/248701",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105189/"
] | I am struggling to make this script working on Wordpress. On Fiddle it works well <https://jsfiddle.net/xqxk2qdg/2/> Any idea why could I have this problem? It is properly enqueued and loaded on page.
```
var array = [];
var array1 = $('#input_8_3').val().split(',');
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
``` | By default, jQuery runs in no conflict mode in WordPress. You have an anonymous function that passes the jQuery object so you can use it.
Your code will error on line two because it doesn't know what $ is. Move the first three lines into the anonymous function to resolve this.
```
(function($){
var array = [];
var array1 = $('#input_8_3').val().split(',');
$("#input_8_3").val(array.join());
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
``` |
248,702 | <p>i need help for optimizing my wordpress website without using plugins incloding wp-total-cache or wp-super-cache.check this link
<a href="https://gtmetrix.com/reports/akhbartop.ir/fF37Flwa" rel="nofollow noreferrer">https://gtmetrix.com/reports/akhbartop.ir/fF37Flwa</a>
my website needs otimize in <strong>Use a Content Delivery Network (CDN)</strong> and <strong>Configure entity tags (ETags)</strong>
also i cant use MAXCDN :) please offer another ways</p>
| [
{
"answer_id": 248713,
"author": "depiction",
"author_id": 101731,
"author_profile": "https://wordpress.stackexchange.com/users/101731",
"pm_score": 2,
"selected": false,
"text": "<p>By default, jQuery runs in no conflict mode in WordPress. You have an anonymous function that passes the ... | 2016/12/08 | [
"https://wordpress.stackexchange.com/questions/248702",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101761/"
] | i need help for optimizing my wordpress website without using plugins incloding wp-total-cache or wp-super-cache.check this link
<https://gtmetrix.com/reports/akhbartop.ir/fF37Flwa>
my website needs otimize in **Use a Content Delivery Network (CDN)** and **Configure entity tags (ETags)**
also i cant use MAXCDN :) please offer another ways | By default, jQuery runs in no conflict mode in WordPress. You have an anonymous function that passes the jQuery object so you can use it.
Your code will error on line two because it doesn't know what $ is. Move the first three lines into the anonymous function to resolve this.
```
(function($){
var array = [];
var array1 = $('#input_8_3').val().split(',');
$("#input_8_3").val(array.join());
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
``` |
248,730 | <p>I need to pass the info from <code>wp_get_current_user()</code> to the front end for a script that uses it. To achieve this, I am using <code>wp_localize_script()</code> to pass the information. I put the code at the top of my <code>functions.php</code> file but it doesn't work.</p>
<p>Here it is. The idea is that on the login event, the <code>add_to_login()</code> function is triggered, whose job it is to add a function to the <code>wp_enqueue_scripts</code>, called <code>add_to_enqueue()</code>. Finally, in <code>add_to_enqueue()</code>, I pass the info to the localized script. I already tried this only using <code>wp_enqeue_scripts</code> so without using <code>wp_login</code> in addition. It seemed the problem was that current user is not available for retrieval until after <code>wp_enqueue_scripts</code> occurs. </p>
<pre><code>function add_to_enqueue() {
$current_user = wp_get_current_user();
$dataToBePassed = array(
'userId' => $current_user['user_login'],
'userName' => $current_user['display_name'],
);
wp_register_script('getUserInfo', get_template_directory_uri().'/assets/js/getUserInfo.js');
wp_localize_script('getUserInfo', 'php_vars', $dataToBePassed);
wp_enqueue_script('getUserInfo');
}
function add_to_login() {
add_action('wp_enqueue_scripts', 'add_to_enqueue');
do_action('wp_enqueue_scripts');
}
add_action('wp_login', 'add_to_login');
</code></pre>
| [
{
"answer_id": 248711,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>In a nutshell, if a client (in the technical sense) has valid username and password then it can provide it to the W... | 2016/12/08 | [
"https://wordpress.stackexchange.com/questions/248730",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108612/"
] | I need to pass the info from `wp_get_current_user()` to the front end for a script that uses it. To achieve this, I am using `wp_localize_script()` to pass the information. I put the code at the top of my `functions.php` file but it doesn't work.
Here it is. The idea is that on the login event, the `add_to_login()` function is triggered, whose job it is to add a function to the `wp_enqueue_scripts`, called `add_to_enqueue()`. Finally, in `add_to_enqueue()`, I pass the info to the localized script. I already tried this only using `wp_enqeue_scripts` so without using `wp_login` in addition. It seemed the problem was that current user is not available for retrieval until after `wp_enqueue_scripts` occurs.
```
function add_to_enqueue() {
$current_user = wp_get_current_user();
$dataToBePassed = array(
'userId' => $current_user['user_login'],
'userName' => $current_user['display_name'],
);
wp_register_script('getUserInfo', get_template_directory_uri().'/assets/js/getUserInfo.js');
wp_localize_script('getUserInfo', 'php_vars', $dataToBePassed);
wp_enqueue_script('getUserInfo');
}
function add_to_login() {
add_action('wp_enqueue_scripts', 'add_to_enqueue');
do_action('wp_enqueue_scripts');
}
add_action('wp_login', 'add_to_login');
``` | In a nutshell, if a client (in the technical sense) has valid username and password then it can provide it to the WP installation to be checked and be placed in a "privileged" context for all the code to run.
Being web app, native WP authentication is mostly browser/cookie centric. So for a mobile app it highly depends on specific app architecture. It can range from merely very same site loaded in the app shell to using REST API (WP's native or even completely custom).
It should be noted that even using the password for log in your app should likely not store it persistently for security reasons. This is commonly implemented via receiving an access token upon successful authentication.
Overall you should first do research on what technologies you will be using in your mobile app, which authentication approaches they favor, and only then how to best interface it with WordPress. |
248,765 | <p>I am testing my theme against WordPress theme unit test, which states that:</p>
<blockquote>
<p>Large number of categories/tags should not adversely impact layout.</p>
</blockquote>
<p>I was able to manage the number of tags but could not help myself in case of categories. Here is the code I'm using to limit the number of tags displayed.
Can it be reused somehow for categories or is there any other way possible?</p>
<pre><code>add_filter('widget_tag_cloud_args', 'themename_tag_limit');
//Limit number of tags inside widget
function themename_tag_limit($args){
if(isset($args['taxonomy']) && $args['taxonomy'] == 'post_tag'){
$args['number'] = 15; //Limit number of tags
}
return $args;
}
</code></pre>
| [
{
"answer_id": 248711,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>In a nutshell, if a client (in the technical sense) has valid username and password then it can provide it to the W... | 2016/12/09 | [
"https://wordpress.stackexchange.com/questions/248765",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108376/"
] | I am testing my theme against WordPress theme unit test, which states that:
>
> Large number of categories/tags should not adversely impact layout.
>
>
>
I was able to manage the number of tags but could not help myself in case of categories. Here is the code I'm using to limit the number of tags displayed.
Can it be reused somehow for categories or is there any other way possible?
```
add_filter('widget_tag_cloud_args', 'themename_tag_limit');
//Limit number of tags inside widget
function themename_tag_limit($args){
if(isset($args['taxonomy']) && $args['taxonomy'] == 'post_tag'){
$args['number'] = 15; //Limit number of tags
}
return $args;
}
``` | In a nutshell, if a client (in the technical sense) has valid username and password then it can provide it to the WP installation to be checked and be placed in a "privileged" context for all the code to run.
Being web app, native WP authentication is mostly browser/cookie centric. So for a mobile app it highly depends on specific app architecture. It can range from merely very same site loaded in the app shell to using REST API (WP's native or even completely custom).
It should be noted that even using the password for log in your app should likely not store it persistently for security reasons. This is commonly implemented via receiving an access token upon successful authentication.
Overall you should first do research on what technologies you will be using in your mobile app, which authentication approaches they favor, and only then how to best interface it with WordPress. |