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 is a any option called 'reset to default' on the image control. This argument will not output any default value to the page.</p>\n\n<p>The second argument of the function <code>get_option( 'option_name', $default )</code>. The <code>$default</code> parameter <strong>will not submit anything to the DB</strong>. 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.</p>\n\n<p>If you want a default value, even if the option are saved and return a empty string, you can do this:</p>\n\n<pre><code>$option = get_option( 'option_name', $default )\necho ( empty( $option ) ? 'default' : $option );\n</code></pre>\n\n<p>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: <a href=\"http://php.net/manual/pt_BR/function.empty.php\" rel=\"nofollow noreferrer\">http://php.net/manual/pt_BR/function.empty.php</a></p>\n\n<p>This way, a default value will be ever applyed, if the option exists.</p>\n\n<blockquote>\n <p>Note: its a best practice to use <code>'type' => 'theme_mod'</code> when creating mods for themes, not <code>'type' => 'option'</code>. If you omit this\n arg, the default will be theme_mod.</p>\n</blockquote>\n"
},
{
"answer_id": 247164,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks @Felipe for explanation & @westonruter for providing the solution in the <a href=\"https://gist.github.com/westonruter/c9b9cf597e9e9129070d67b68920168e/9d9a4d8f0a751b549dff17c34f4790568316d8ac#file-functions-php-L37\" rel=\"nofollow noreferrer\">gist</a>.</p>\n\n<p>Solution: Create <code>defaults</code> array and use it in <em>Customizer</em> & on <em>Front End</em>. </p>\n\n<p><strong>Step-1:</strong> Register theme defaults array.</p>\n\n<pre><code>if ( ! function_exists( 'my_theme_defaults' ) ) {\n\n function my_theme_defaults() {\n\n return array(\n 'option-1' => 1,\n 'option-2' => 'author',\n 'option-3' => '#3a3a3a',\n 'option-4' => 'ALL RIGHT RESERVED'\n 'option-5' => get_template_directory_uri() . '/assets/images/logo-black.png'\n );\n }\n}\n</code></pre>\n\n<hr />\n\n<p><strong>Setp-2</strong>: Access in Customizer & FrontEnd.</p>\n\n<h3>Access in Customizer</h3>\n\n<pre><code>// Get theme default values\n$theme_defaults = my_theme_defaults();\n\n...\n$wp_customize->add_setting( 'my-theme-options[option-1]', array(\n 'default' => $theme_defaults['option-1'],\n ...\n) );\n...\n$wp_customize->add_setting( 'my-theme-options[option-2]', array(\n 'default' => $theme_defaults['option-2'],\n ...\n) );\n...\n</code></pre>\n\n<h3>Access on Front End</h3>\n\n<pre><code>// Get theme stored values\n// Note: I use the `'type' => 'option',` for all the options. So, Getting stored values of option 'my-theme-options' using `get_option()`. You can use `get_theme_mod()` if you use it for `add_settings()`.\n$theme_stored = get_option( 'my-theme-options' );\n\n// Get theme default values\n$theme_defaults = my_theme_defaults();\n\n// Merge both\n$theme_options = wp_parse_args( $theme_stored, $theme_defaults );\n\n// Access option value \n// e.g.\necho $theme_options['option-1'];\necho $theme_options['option-2'];\necho $theme_options['option-3'];\n</code></pre>\n\n<hr />\n\n<p><strong>NOTE: Don't forget to use filters where ever possible to extend in future. Also, Add text translations.</strong></p>\n"
},
{
"answer_id": 256379,
"author": "Jilani A",
"author_id": 112275,
"author_profile": "https://wordpress.stackexchange.com/users/112275",
"pm_score": 0,
"selected": false,
"text": "<p>Very easy solution, try it. Hope It will help you.</p>\n\n<p>Simply use this code in your front-end.</p>\n\n<p><strong>From your own directory-</strong></p>\n\n<pre><code><img src=\"<?php echo esc_url(get_theme_mod('this-is-the-test-option',''.get_template_directory_uri().'/images/logo.png')); ?>\" alt=\"Google\"/>\n</code></pre>\n\n<p><strong>From online link-</strong></p>\n\n<pre><code><img src=\"<?php echo esc_url(get_theme_mod('this-is-the-test-option','https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png')); ?>\" alt=\"Google\"/>\n</code></pre>\n"
}
] |
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://codex.wordpress.org/Function_Reference/esc_url_raw\" rel=\"nofollow noreferrer\">esc_url_raw</a></p>\n\n<blockquote>\n <p>The esc_url_raw() function is similar to esc_url() (and actually uses it), but unlike esc_url() it does not replace entities for display. The resulting URL is safe to use in database queries, redirects and HTTP requests.</p>\n</blockquote>\n\n<p>So, it should probably be written like this:</p>\n\n<pre><code>// escape url before using update_post_meta\nupdate_post_meta( $post_id, 'url', esc_url_raw( $url ) );\n\n// escape url on output\necho esc_url( get_post_meta( $post_id, 'url', true ) );\n</code></pre>\n\n<p>So, to recap, <code>esc_url_raw</code> for database storage, and <code>esc_url</code> for display.</p>\n"
},
{
"answer_id": 247027,
"author": "kovshenin",
"author_id": 1316,
"author_profile": "https://wordpress.stackexchange.com/users/1316",
"pm_score": 3,
"selected": true,
"text": "<p>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 <code>wp_remote_*</code> context, or a redirect, or any other non-display context, you should be using <code>esc_url_raw()</code> instead.</p>\n\n<p>Also note that <code>get_post_meta</code> will return an array, unless the third argument <code>$single</code> is set to true. If you're dealing with a single key-value pair you'll want:</p>\n\n<pre><code>echo esc_url( get_post_meta( $post_id, 'url', true ) );\n</code></pre>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 247031,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>I just want to mention the possibility of <strong>validating</strong> the user input before storing it and then <strong>escape</strong> it when you display it.</p>\n\n<p>There's e.g. the <a href=\"http://php.net/manual/en/function.filter-var.php\" rel=\"nofollow noreferrer\"><code>filter_var()</code></a> PHP function with the <code>FILTER_VALIDATE_URL</code> flag.</p>\n\n<p>There's also the <a href=\"https://developer.wordpress.org/reference/functions/wp_http_validate_url/\" rel=\"nofollow noreferrer\"><code>wp_http_validate_url()</code></a> function, that's applied for the <code>wp_safe_remote_{post,request,get}</code> calls, <em>to avoid redirection and request forgery attacks</em>, as mentioned in the inline docs.</p>\n"
}
] |
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 is maybe add by a plugin or theme.</p>\n\n<p>If you find <code>register_post_status</code> in your files, there are custom post status, and maybe an array to convert <code>closed</code> to <code>pending</code> or something else.</p>\n\n<p>if not look for <code>add_meta_boxes</code> action.</p>\n\n<p>You can also try to var_dump a closed post custom fields to see if it is not add to à custom meta field.\nIf it's the case, you will get your publish posts by excluding them with <code>meta_query</code> parameter.</p>\n\n<p>Hope it gives some hints!</p>\n"
},
{
"answer_id": 247052,
"author": "Michelle",
"author_id": 16,
"author_profile": "https://wordpress.stackexchange.com/users/16",
"pm_score": 3,
"selected": true,
"text": "<p>The correct <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Status_Parameters\" rel=\"nofollow noreferrer\"><code>post_status</code></a> for a 'published' post is 'publish':</p>\n\n<pre><code>'post_status' => 'publish',\n</code></pre>\n"
}
] |
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 username and password have a value, then this action can be captured by wp_login_failed </p></li>\n<li><p>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, </p></li>\n</ol>\n\n<p>see comments in code:</p>\n\n<pre><code>add_filter( 'authenticate', function( $user, $username, $password ) {\n // forcefully capture login failed to forcefully open wp_login_failed action, \n // so that this event can be captured\n if ( empty( $username ) || empty( $password ) ) {\n do_action( 'wp_login_failed', $user );\n }\n return $user;\n} );\n\n// to handle even you can handle the error like\nadd_action( 'wp_login_failed', function( $username ) {\n if ( is_wp_error( $username ) ) {\n // you return 401 with wp function, this action takes place before header sent.\n $wp_query->set_401();\n status_header( 401 );\n nocache_headers();\n\n }\n} );\n</code></pre>\n\n<p>my answer is a combination of : <a href=\"https://wordpress.stackexchange.com/questions/172608/redirect-user-using-the-wp-login-failed-action-hook-if-the-error-is-empty-use\">Redirect user using the 'wp_login_failed' action hook if the error is 'empty_username' or 'empty_password'</a> and <a href=\"https://wordpress.stackexchange.com/questions/91900/how-to-force-a-404-on-wordpress\">How to force a 404 on WordPress</a></p>\n\n<p><strong>update:</strong> I wrote super simple plugin to do this <a href=\"https://github.com/amitrahav/WP-401-On-Failed-Login\" rel=\"nofollow noreferrer\">WP-401-On-Failed-Login</a>. It uses some wp auth hooks, and set_header() before content being sent.</p>\n"
},
{
"answer_id": 247801,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 1,
"selected": false,
"text": "<p>If you have access to the server your site is running on, you could use modsecurity to return 401 from the web server (instead of through PHP).</p>\n\n<p>Here's a tutorial I wrote a while back about blocking IPs and returning 401 through modsecurity:</p>\n\n<p><a href=\"https://smyl.es/how-to-block-wp-login-php-brute-logins-with-cpanel-mod-security-and-configserver-firewall/\" rel=\"nofollow noreferrer\">https://smyl.es/how-to-block-wp-login-php-brute-logins-with-cpanel-mod-security-and-configserver-firewall/</a></p>\n"
}
] |
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', 'modify_admin_bar' );\n\nfunction modify_admin_bar( $wp_admin_bar ){\n // do something with $wp_admin_bar;\n $wp_admin_bar->get_nodes();\n\n}\n</code></pre>\n\n<p>Have look to the codex <a href=\"https://codex.wordpress.org/Class_Reference/WP_Admin_Bar\" rel=\"nofollow noreferrer\">WP_Admin_Bar</a> to see all methods available.</p>\n"
},
{
"answer_id": 247122,
"author": "adelval",
"author_id": 40965,
"author_profile": "https://wordpress.stackexchange.com/users/40965",
"pm_score": 0,
"selected": false,
"text": "<p>To be more specific than @Benoti, you need to use the remove_node function from the <code>WP_Admin_Bar</code> class. It is clearly explained in the <a href=\"https://codex.wordpress.org/Function_Reference/remove_node\" rel=\"nofollow noreferrer\">codex</a>, including how to find the id of the node you want to remove. Specifically, to remove the Avada menu you need to create a child theme of Avada with a <code>functions.php</code> file containing the following code:</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'remove_avada_from_admin_bar', 999 );\n\nfunction remove_avada_from_admin_bar( $wp_admin_bar ) {\n $wp_admin_bar->remove_node( 'wp-admin-bar-avada' );\n}\n</code></pre>\n"
},
{
"answer_id": 314947,
"author": "rajalanun",
"author_id": 151144,
"author_profile": "https://wordpress.stackexchange.com/users/151144",
"pm_score": 0,
"selected": false,
"text": "<p>Try use wp_before_admin_bar_render.</p>\n\n<pre><code>add_action( 'wp_before_admin_bar_render', 'modify_admin_bar' );\n</code></pre>\n"
}
] |
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', 'modify_admin_bar' );\n\nfunction modify_admin_bar( $wp_admin_bar ){\n // do something with $wp_admin_bar;\n $wp_admin_bar->get_nodes();\n\n}\n</code></pre>\n\n<p>Have look to the codex <a href=\"https://codex.wordpress.org/Class_Reference/WP_Admin_Bar\" rel=\"nofollow noreferrer\">WP_Admin_Bar</a> to see all methods available.</p>\n"
},
{
"answer_id": 247122,
"author": "adelval",
"author_id": 40965,
"author_profile": "https://wordpress.stackexchange.com/users/40965",
"pm_score": 0,
"selected": false,
"text": "<p>To be more specific than @Benoti, you need to use the remove_node function from the <code>WP_Admin_Bar</code> class. It is clearly explained in the <a href=\"https://codex.wordpress.org/Function_Reference/remove_node\" rel=\"nofollow noreferrer\">codex</a>, including how to find the id of the node you want to remove. Specifically, to remove the Avada menu you need to create a child theme of Avada with a <code>functions.php</code> file containing the following code:</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'remove_avada_from_admin_bar', 999 );\n\nfunction remove_avada_from_admin_bar( $wp_admin_bar ) {\n $wp_admin_bar->remove_node( 'wp-admin-bar-avada' );\n}\n</code></pre>\n"
},
{
"answer_id": 314947,
"author": "rajalanun",
"author_id": 151144,
"author_profile": "https://wordpress.stackexchange.com/users/151144",
"pm_score": 0,
"selected": false,
"text": "<p>Try use wp_before_admin_bar_render.</p>\n\n<pre><code>add_action( 'wp_before_admin_bar_render', 'modify_admin_bar' );\n</code></pre>\n"
}
] |
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 access it, you have to use the <code>global</code> keyword in you template file:</p>\n\n<pre><code>global $foo;\necho $foo;\n</code></pre>\n\n<p>As <code>header.php</code> probalbly is also called in a function scope, you have to make sure there the variable is used in global scope when definig it:</p>\n\n<pre><code>global $foo;\n$foo = 'bar';\n</code></pre>\n"
},
{
"answer_id": 247089,
"author": "ricotheque",
"author_id": 34238,
"author_profile": "https://wordpress.stackexchange.com/users/34238",
"pm_score": 0,
"selected": false,
"text": "<p>If you're going to pass on numerous values across different template files, I suggest using a static class to store an array.</p>\n\n<pre><code>// In your functions.php\nclass Var\n{\n public static $foo;\n public static function set_var($value;)\n {\n self::$foo = $value;\n }\n\n}\n\n// In your header.php\n\\Var::set_var(array(\n 'var1' => 'value1',\n 'var2' => 'value2',\n));\n</code></pre>\n\n<p>Now you can just call the class statically anywhere else to access the data.</p>\n\n<pre><code>// Displays 'value1'\necho \\Var::$foo['var1'];\n\n// Displays 'value2'\necho \\Var::$foo['var2'];\n</code></pre>\n\n<p>Might seem like overkill for passing a few variables, but at least you have the option of expanding the array if you need to pass much more information.</p>\n"
},
{
"answer_id": 247094,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 1,
"selected": false,
"text": "<p>Don't muddy up the <code>$_GLOBAL</code> space. If you want to nix the class route and use a function with a statically scoped variable you can keep it contained.</p>\n\n<pre><code>// getter + setter function \n\nfunction prefix_my_var( $value = null ) {\n static $s = null;\n if ( ! is_null( $value ) ) {\n $s = $value;\n }\n\n return $s;\n}\n\n// set + get\n\n$value = prefix_my_var( 'foo' ); // foo\n\n// get\n\n$value = prefix_my_var(); // foo\n</code></pre>\n\n<p>Now if you pass a value it'll set+get it. And if you don't pass a value it'll just get the current value.</p>\n\n<pre><code>echo \"<pre>\";\nprint_r( array (\n prefix_my_var(),\n prefix_my_var( 'foo' ),\n prefix_my_var(),\n prefix_my_var( 'bar' ),\n prefix_my_var(),\n prefix_my_var( 'baz' ),\n ) );\n\nArray\n(\n [0] => \n [1] => foo\n [2] => foo\n [3] => bar\n [4] => bar\n [5] => baz\n)\n</code></pre>\n"
}
] |
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();\n\n if ( isset( $_POST['action'] ) && $_POST['action'] == 'profile-form' ) {\n\n if ( ! isset( $_SESSION['form-submit'] ) ) {\n\n // form processing code here\n\n $_SESSION['form-submit'] = 1;\n\n $redirect_page = get_permalink( 586 );\n wp_redirect( $redirect_page );\n exit;\n\n } else {\n\n unset( $_SESSION['form-submit'] );\n }\n }\n}\nadd_action( 'init','vv_process_profile_forms' );\n</code></pre>\n"
},
{
"answer_id": 279391,
"author": "Jeff Pedigo",
"author_id": 107550,
"author_profile": "https://wordpress.stackexchange.com/users/107550",
"pm_score": 2,
"selected": true,
"text": "<p>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. </p>\n\n<p>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.</p>\n"
}
] |
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();\n\n if ( isset( $_POST['action'] ) && $_POST['action'] == 'profile-form' ) {\n\n if ( ! isset( $_SESSION['form-submit'] ) ) {\n\n // form processing code here\n\n $_SESSION['form-submit'] = 1;\n\n $redirect_page = get_permalink( 586 );\n wp_redirect( $redirect_page );\n exit;\n\n } else {\n\n unset( $_SESSION['form-submit'] );\n }\n }\n}\nadd_action( 'init','vv_process_profile_forms' );\n</code></pre>\n"
},
{
"answer_id": 279391,
"author": "Jeff Pedigo",
"author_id": 107550,
"author_profile": "https://wordpress.stackexchange.com/users/107550",
"pm_score": 2,
"selected": true,
"text": "<p>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. </p>\n\n<p>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.</p>\n"
}
] |
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<p>go to on line <code>283</code> and check how you have added add_action function.</p>\n\n<p>It must be like this.</p>\n\n<pre><code>add_action('tag','function_callback' );\n</code></pre>\n\n<p><code>add_action</code> is a function which allows you to attach a function to an action hook and it must not be string eg. <code>'add_action'</code></p>\n\n<p>Please read document about add_action <a href=\"http://codex.wordpress.org/Function_Reference/add_action\" rel=\"nofollow noreferrer\">http://codex.wordpress.org/Function_Reference/add_action</a> </p>\n"
},
{
"answer_id": 247134,
"author": "JHoffmann",
"author_id": 63847,
"author_profile": "https://wordpress.stackexchange.com/users/63847",
"pm_score": 0,
"selected": false,
"text": "<p>This error often occurs with syntax errors like missing brackets in the code. In your case probably in the lines preceding the <code>add_action</code> call. Check the syntax there or post the previous code block here please.</p>\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_options' ) ) {\n wp_raise_memory_limit( 'admin' );\n}\n</code></pre>\n\n<p>In other words, WordPress raises the memory limit to <code>WP_MAX_MEMORY_LIMIT</code> within the admin, but only for users with the <code>manage_options</code> capability i.e. administrators.</p>\n\n<p>Your best bet is to <a href=\"https://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP\" rel=\"nofollow noreferrer\">raise the default memory limit</a> in your <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_MEMORY_LIMIT', '256M' ); \n</code></pre>\n"
},
{
"answer_id": 413266,
"author": "Артур Димерчан",
"author_id": 207161,
"author_profile": "https://wordpress.stackexchange.com/users/207161",
"pm_score": 0,
"selected": false,
"text": "<p>Probably you may try <code>admin_init</code> hook and call <code>wp_raise_memory_limit( 'admin' );</code> for the selected user\nExample:</p>\n<pre><code>add_action('admin_init', function(){\n if ( get_current_user_id() === 111111 ){\n wp_raise_memory_limit( 'admin' ); \n }\n});\n</code></pre>\n"
}
] |
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't be execute.</p>\n\n<p>At the top of the function, you can do it with <code>get_post_meta()</code></p>\n\n<pre><code> global $post;\n\n $custom_fields = get_post_meta($post->ID);\n</code></pre>\n"
},
{
"answer_id": 247213,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page()</code></a> requires <code>WP_Query</code> to be initialized and I assume your code runs before this. You can use this function within the filter callback instead:</p>\n\n<pre><code>add_filter('the_content', function($c){\n return is_page() ? luc_add_cutom_fields_to_content($c) : $c;\n});\n</code></pre>\n"
}
] |
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</code></pre>\n"
},
{
"answer_id": 247203,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 0,
"selected": false,
"text": "<p>You can get POST ID by <code>$_REQUEST</code> .</p>\n\n<pre><code>add_action('init',function(){\n global $post;\n\n if($post){\n session_start();\n $_SESSION['p_id'] = $post->ID;\n }\n\n});\n\nadd_filter( 'wp_handle_upload_prefilter', 'do_pre_upload' );\n\nfunction do_pre_upload( $file ) {\n\n add_filter( 'upload_dir', 'do_custom_upload_dir' );\n return $file;\n}\n\nfunction do_custom_upload_dir( $param ) {\n\n // Get the current post_id\n $id = ( isset( $_SESSION['p_id'] ) ? $_SESSION['p_id'] : '' );\n\n unset($_SESSION['p_id']);\n\n $parent = get_post( $id )->post_parent;\n if( \"client_gallery\" == get_post_type( $id ) || \"client_gallery\" == get_post_type( $parent ) ) {\n $mydir = '/client_galleryy/'.$post->ID.'';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n }\n\n\n\n return $param;\n\n\n}\n</code></pre>\n\n<p>Try it it should work ...</p>\n"
},
{
"answer_id": 247211,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>Based on your comments, it sounds like you just want a custom directory for your post type called <code>client_gallery</code> which is fairly straight-forward actually. The below just uses the <code>upload_dir</code> hook to achieve this:</p>\n\n<pre><code>/**\n * Modify Upload Directory Based on Post Type\n *\n * @param Array $dir\n *\n * @return Array $dir\n */\nfunction wpse_247197( $dir ) {\n $request_arr = array( 'upload-attachment', 'editpost', 'editedtag' );\n $request = array_change_key_case( $_REQUEST, CASE_LOWER ); // WordPress uses post_id and post_ID\n $type = null;\n\n // Are we where we want to be?\n if( ! ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $request_arr ) ) ) {\n return $dir;\n }\n\n if( isset( $request['post_id'] ) ) { // Get Post ID\n $id = $request['post_id'];\n\n if( isset( $request['post_type'] ) ) { // Get the post type if it was passed\n $type = $request['post_type'];\n } else { // If not passed, get post type by ID\n $type = get_post_type( $id );\n }\n } else { // If we can't get a post ID return default directory\n return $dir;\n }\n\n if( isset( $type, $id ) && ! empty( $type ) && ! empty( $id ) ) {\n\n // Here we can test our type and change the directory name etc. if we really wanted to\n if( 'product' != $type ) {\n return $dir;\n }\n\n $uploads = apply_filters( \"{$type}_upload_directory\", \"{$type}/{$id}\" ); // Set our uploads URL for this type\n $dir['url'] = path_join( $dir['baseurl'], $uploads ); // Apply the URL to the directory array\n $dir['path'] = path_join( $dir['basedir'], $uploads ); // Apply the Path to the directory array\n\n error_log( print_r( $dir, 1 ) );\n }\n\n return $dir;\n}\nadd_filter( 'upload_dir', 'wpse_247197' );\n</code></pre>\n\n<p>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.</p>\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</code></pre>\n"
},
{
"answer_id": 247203,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 0,
"selected": false,
"text": "<p>You can get POST ID by <code>$_REQUEST</code> .</p>\n\n<pre><code>add_action('init',function(){\n global $post;\n\n if($post){\n session_start();\n $_SESSION['p_id'] = $post->ID;\n }\n\n});\n\nadd_filter( 'wp_handle_upload_prefilter', 'do_pre_upload' );\n\nfunction do_pre_upload( $file ) {\n\n add_filter( 'upload_dir', 'do_custom_upload_dir' );\n return $file;\n}\n\nfunction do_custom_upload_dir( $param ) {\n\n // Get the current post_id\n $id = ( isset( $_SESSION['p_id'] ) ? $_SESSION['p_id'] : '' );\n\n unset($_SESSION['p_id']);\n\n $parent = get_post( $id )->post_parent;\n if( \"client_gallery\" == get_post_type( $id ) || \"client_gallery\" == get_post_type( $parent ) ) {\n $mydir = '/client_galleryy/'.$post->ID.'';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n }\n\n\n\n return $param;\n\n\n}\n</code></pre>\n\n<p>Try it it should work ...</p>\n"
},
{
"answer_id": 247211,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>Based on your comments, it sounds like you just want a custom directory for your post type called <code>client_gallery</code> which is fairly straight-forward actually. The below just uses the <code>upload_dir</code> hook to achieve this:</p>\n\n<pre><code>/**\n * Modify Upload Directory Based on Post Type\n *\n * @param Array $dir\n *\n * @return Array $dir\n */\nfunction wpse_247197( $dir ) {\n $request_arr = array( 'upload-attachment', 'editpost', 'editedtag' );\n $request = array_change_key_case( $_REQUEST, CASE_LOWER ); // WordPress uses post_id and post_ID\n $type = null;\n\n // Are we where we want to be?\n if( ! ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $request_arr ) ) ) {\n return $dir;\n }\n\n if( isset( $request['post_id'] ) ) { // Get Post ID\n $id = $request['post_id'];\n\n if( isset( $request['post_type'] ) ) { // Get the post type if it was passed\n $type = $request['post_type'];\n } else { // If not passed, get post type by ID\n $type = get_post_type( $id );\n }\n } else { // If we can't get a post ID return default directory\n return $dir;\n }\n\n if( isset( $type, $id ) && ! empty( $type ) && ! empty( $id ) ) {\n\n // Here we can test our type and change the directory name etc. if we really wanted to\n if( 'product' != $type ) {\n return $dir;\n }\n\n $uploads = apply_filters( \"{$type}_upload_directory\", \"{$type}/{$id}\" ); // Set our uploads URL for this type\n $dir['url'] = path_join( $dir['baseurl'], $uploads ); // Apply the URL to the directory array\n $dir['path'] = path_join( $dir['basedir'], $uploads ); // Apply the Path to the directory array\n\n error_log( print_r( $dir, 1 ) );\n }\n\n return $dir;\n}\nadd_filter( 'upload_dir', 'wpse_247197' );\n</code></pre>\n\n<p>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.</p>\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 = 129;\nif( get_post_status( $post_id ) == 'publish' ) {\n\n $post_content = get_post($post_id);\n $content = $post_content->post_content;\n echo apply_filters('the_content',$content);\n}\n</code></pre>\n"
},
{
"answer_id": 247210,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": true,
"text": "<p>The reason your post is not displaying properly is because functions such as <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a>, <a href=\"https://codex.wordpress.org/Function_Reference/the_permalink\" rel=\"nofollow noreferrer\"><code>the_permalink()</code></a>, and <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"nofollow noreferrer\"><code>the_content()</code></a> ( called <a href=\"https://codex.wordpress.org/Template_Tags\" rel=\"nofollow noreferrer\">Template Tags</a> ) can only be used whenever inside <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">\"The Loop\"</a> or whenever set up properly. There are two options to display your content properly:</p>\n\n<p><strong>Functions: <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow noreferrer\"><code>get_post()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/setup_postdata/\" rel=\"nofollow noreferrer\"><code>setup_postdata()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a></strong></p>\n\n<p>First you would need to get the WP_Post Object and pass it into the <code>setup_postdata()</code> function so that WordPress can setup the template tags to pull in the correct content. Finally, we would need to reset the <code>global $post</code> object by calling <code>wp_reset_postdata()</code>.</p>\n\n<pre><code>global $post; // Get the current WP_Post object.\n\n$post = get_post( 129 ); // Get our Post Object.\nsetup_postdata( $post ); // Setup our template tags.\n\nif( 'publish' == $post->post_status ) {\n the_content();\n}\n\nwp_rest_postdata(); // Reset the global WP_Post object.\n</code></pre>\n\n<p><strong>Tad Easier using <code>apply_filters()</code></strong></p>\n\n<p>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.</p>\n\n<pre><code>$post_id = 129;\n\nif( 'publish' == get_post_status( $post_id ) ) {\n $post_content = get_post_field( 'post_content', $post_id );\n echo apply_filters( 'the_content', $post_content );\n}\n</code></pre>\n\n<p>The above grabs the content from the database then runs it through a WordPress filter which processes <code>the_content()</code> hook to give us our desired output, shortcodes processed and all.</p>\n"
}
] |
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 = 129;\nif( get_post_status( $post_id ) == 'publish' ) {\n\n $post_content = get_post($post_id);\n $content = $post_content->post_content;\n echo apply_filters('the_content',$content);\n}\n</code></pre>\n"
},
{
"answer_id": 247210,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": true,
"text": "<p>The reason your post is not displaying properly is because functions such as <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title()</code></a>, <a href=\"https://codex.wordpress.org/Function_Reference/the_permalink\" rel=\"nofollow noreferrer\"><code>the_permalink()</code></a>, and <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"nofollow noreferrer\"><code>the_content()</code></a> ( called <a href=\"https://codex.wordpress.org/Template_Tags\" rel=\"nofollow noreferrer\">Template Tags</a> ) can only be used whenever inside <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">\"The Loop\"</a> or whenever set up properly. There are two options to display your content properly:</p>\n\n<p><strong>Functions: <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow noreferrer\"><code>get_post()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/setup_postdata/\" rel=\"nofollow noreferrer\"><code>setup_postdata()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a></strong></p>\n\n<p>First you would need to get the WP_Post Object and pass it into the <code>setup_postdata()</code> function so that WordPress can setup the template tags to pull in the correct content. Finally, we would need to reset the <code>global $post</code> object by calling <code>wp_reset_postdata()</code>.</p>\n\n<pre><code>global $post; // Get the current WP_Post object.\n\n$post = get_post( 129 ); // Get our Post Object.\nsetup_postdata( $post ); // Setup our template tags.\n\nif( 'publish' == $post->post_status ) {\n the_content();\n}\n\nwp_rest_postdata(); // Reset the global WP_Post object.\n</code></pre>\n\n<p><strong>Tad Easier using <code>apply_filters()</code></strong></p>\n\n<p>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.</p>\n\n<pre><code>$post_id = 129;\n\nif( 'publish' == get_post_status( $post_id ) ) {\n $post_content = get_post_field( 'post_content', $post_id );\n echo apply_filters( 'the_content', $post_content );\n}\n</code></pre>\n\n<p>The above grabs the content from the database then runs it through a WordPress filter which processes <code>the_content()</code> hook to give us our desired output, shortcodes processed and all.</p>\n"
}
] |
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</code> function. So based on the <code>custom_pagination</code> function, here's how I'd rewrite it:</p>\n\n<pre><code>function custom_pagination() {\n global $wp_query;\n\n // No idea why this line was in the if statement originally...\n $paged = ( get_query_var('paged') ? get_query_var('paged') : 1 );\n\n $big = 999999999; // need an unlikely integer\n\n $pages = paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => $paged,\n 'total' => $wp_query->max_num_pages,\n 'prev_next' => false,\n 'type' => 'array',\n 'prev_next' => TRUE,\n 'prev_text' => __('«'),\n 'next_text' => __('»'),\n ) );\n\n if( is_array( $pages ) ) {\n\n echo '<ul class=\"pagination\">' .\n str_replace( 'class=\"page-numbers\"', 'class=\"page-link\"', implode( '', $pages ) .\n '</ul>';\n\n }\n}\n</code></pre>\n\n<p>Didn't test this, please let me know if you have any issues.</p>\n"
},
{
"answer_id": 247231,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>paginate_links()</code> function, located in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/general-template.php#L3233\" rel=\"nofollow noreferrer\"><code>wp-includes/general-template.php</code></a>, doesn't allow for certain parts of the HTML (such as the <code>page-numbers</code> class) to be customized. </p>\n\n<p>A simple string replacement will not work due to the way that the classes are generated, as highlighted in this excerpt of code from <code>paginate_links()</code>:</p>\n\n<pre><code> $page_links[] = '<a class=\"prev page-numbers\" href=\"' . esc_url( apply_filters( 'paginate_links', $link ) ) . '\">' . $args['prev_text'] . '</a>';\nendif;\nfor ( $n = 1; $n <= $total; $n++ ) :\n if ( $n == $current ) :\n $page_links[] = \"<span class='page-numbers current'>\" . $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number'] . \"</span>\";\n</code></pre>\n\n<p>Here is an updated version of your <code>custom_pagination()</code> function, which uses DOMXpath to to find instances elements with the <code>page-numbers</code> class, then a string replacement is done to change the class to <code>page-link</code>. For better compatibility with Bootstrap, the <code>current</code> class is also replaced with <code>active</code>. Finally, <code>class=\"mynewclass\"</code> is added to the <code><li></code> which contains the current item.</p>\n\n<pre><code>function wpse247219_custom_pagination() {\n global $wp_query;\n $big = 999999999; // need an unlikely integer\n $pages = paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'total' => $wp_query->max_num_pages,\n 'prev_next' => false,\n 'type' => 'array',\n 'prev_next' => true,\n 'prev_text' => __( '«', 'text-domain' ),\n 'next_text' => __( '»', 'text-domain'),\n ) );\n $output = '';\n\n if ( is_array( $pages ) ) {\n $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var( 'paged' );\n\n $output .= '<ul class=\"pagination\">';\n foreach ( $pages as $page ) {\n $output .= \"<li>$page</li>\";\n }\n $output .= '</ul>';\n\n // Create an instance of DOMDocument \n $dom = new \\DOMDocument();\n\n // Populate $dom with $output, making sure to handle UTF-8, otherwise\n // problems will occur with UTF-8 characters.\n $dom->loadHTML( mb_convert_encoding( $output, 'HTML-ENTITIES', 'UTF-8' ) );\n\n // Create an instance of DOMXpath and all elements with the class 'page-numbers' \n $xpath = new \\DOMXpath( $dom );\n\n // http://stackoverflow.com/a/26126336/3059883\n $page_numbers = $xpath->query( \"//*[contains(concat(' ', normalize-space(@class), ' '), ' page-numbers ')]\" );\n\n // Iterate over the $page_numbers node...\n foreach ( $page_numbers as $page_numbers_item ) {\n\n // Add class=\"mynewclass\" to the <li> when its child contains the current item.\n $page_numbers_item_classes = explode( ' ', $page_numbers_item->attributes->item(0)->value );\n if ( in_array( 'current', $page_numbers_item_classes ) ) { \n $list_item_attr_class = $dom->createAttribute( 'class' );\n $list_item_attr_class->value = 'mynewclass';\n $page_numbers_item->parentNode->appendChild( $list_item_attr_class );\n }\n\n // Replace the class 'current' with 'active'\n $page_numbers_item->attributes->item(0)->value = str_replace( \n 'current',\n 'active',\n $page_numbers_item->attributes->item(0)->value );\n\n // Replace the class 'page-numbers' with 'page-link'\n $page_numbers_item->attributes->item(0)->value = str_replace( \n 'page-numbers',\n 'page-link',\n $page_numbers_item->attributes->item(0)->value );\n }\n\n // Save the updated HTML and output it.\n $output = $dom->saveHTML();\n }\n\n return $output;\n}\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>echo wpse247219_custom_pagination();\n</code></pre>\n\n<p><strong>Generated HTML:</strong></p>\n\n<pre><code><ul class=\"pagination\">\n <li class=\"mynewclass\"><span class=\"page-link active\">1</span></li>\n <li><a class=\"page-link\" href=\"http://localhost/page/2/\">2</a></li>\n <li><a class=\"page-link\" href=\"http://localhost/page/3/\">3</a></li>\n <li><span class=\"page-link dots\">…</span></li>\n <li><a class=\"page-link\" href=\"http://localhost/page/5/\">5</a></li>\n <li><a class=\"next page-link\" href=\"http://localhost/page/2/\">»</a></li>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 332431,
"author": "iWebbers",
"author_id": 163697,
"author_profile": "https://wordpress.stackexchange.com/users/163697",
"pm_score": 0,
"selected": false,
"text": "<p>In your last line of code you forgot a closing ). Here is the correct line:</p>\n\n<pre><code>echo '<ul class=\"pagination\">' . str_replace( 'class=\"page-numbers\"', 'class=\"page-link\"' ), implode( '', $pages ) . '</ul>';\n</code></pre>\n"
},
{
"answer_id": 332436,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>A simpler solution using jQuery </p>\n\n<pre><code>jQuery(document).ready(function ($) {\n\n $(\".pagination .page-item .page-numbers\").addClass(\"page-link\");\n $(\".pagination .page-item .page-link\").removeClass(\"page-numbers\");\n\n});\n</code></pre>\n\n<p>Same approach can be used for other classes like <code>current</code> etc.</p>\n"
},
{
"answer_id": 375206,
"author": "Mickael Bertainchant",
"author_id": 194938,
"author_profile": "https://wordpress.stackexchange.com/users/194938",
"pm_score": 1,
"selected": false,
"text": "<p>Work on this today, compatible wordpress 5.5.1 with bootstrap 4 :</p>\n<pre class=\"lang-php prettyprint-override\"><code> <?php\n $pagination = paginate_links( array(\n 'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'total' => $query_accueil->max_num_pages,\n 'prev_text' => '<i class="fas fa-angle-double-left"></i>',\n 'next_text' => '<i class="fas fa-angle-double-right"></i>',\n 'type' => 'array'\n ) );\n ?>\n <?php if ( ! empty( $pagination ) ) : ?>\n <nav aria-label="page navigation">\n <ul class="pagination">\n <?php foreach ( $pagination as $key => $page_link ) : ?>\n <li class="page-item\n <?php\n $link = htmlspecialchars($page_link);\n $link = str_replace( ' current', '', $link);\n if ( strpos( $page_link, 'current' ) !== false ) { echo ' active'; }\n ?>\n ">\n <?php\n if ( $link ) {\n $link = str_replace( 'page-numbers', 'page-link', $link);\n }\n echo htmlspecialchars_decode($link);\n ?>\n </li>\n <?php endforeach ?>\n </ul>\n </nav>\n <?php endif ?>\n</code></pre>\n"
}
] |
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\" rel=\"noreferrer\">standalone example plugin</a> 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.</p>\n\n<hr>\n\n<p>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 <code>customize_render_partials_before</code> action has the following docs:</p>\n\n<blockquote>\n <p><strong>Fires immediately before partials are rendered.</strong></p>\n \n <p>Plugins may do things like call <code>wp_enqueue_scripts()</code> and gather a list of the scripts\n and styles which may get enqueued in the response.</p>\n</blockquote>\n\n<p>And eventually core may go ahead and do <code>wp_enqueue_scripts()</code> itself by default. For the initial implementation of selective refresh, however, the enqueueing was left to plugins.</p>\n\n<p>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 <code>customize_render_partials_response</code> filter is for, as its docs indicate:</p>\n\n<blockquote>\n <p><strong>Filters the response from rendering the partials.</strong></p>\n \n <p>Plugins may use this filter to inject <code>$scripts</code> and <code>$styles</code>, which are dependencies\n for the partials being rendered. The response data will be available to the client via\n the <code>render-partials-response</code> JS event, so the client can then inject the scripts and\n styles into the DOM if they have not already been enqueued there.</p>\n \n <p>If plugins do this, they'll need to take care for any scripts that do <code>document.write()</code>\n and make sure that these are not injected, or else to override the function to no-op,\n or else the page will be destroyed.</p>\n \n <p>Plugins should be aware that <code>$scripts</code> and <code>$styles</code> may eventually be included by\n default in the response.</p>\n</blockquote>\n\n<p>The filtered <code>$response</code> array is exposed in JavaScript via a <code>render-partials-response</code> event triggered on <code>wp.customize.selectiveRefresh</code>. 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 <code>render-partials-response</code> 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 <code>wp.customize.selectiveRefresh.requestFullRefresh()</code>. The following JS would be enqueued only in the customizer preview:</p>\n\n<pre><code>/* global wp, _ */\n/* exported WPSE_247251 */\nvar WPSE_247251 = (function( api ) {\n\n var component = {\n data: {\n enqueued_styles: {},\n enqueued_scripts: {}\n }\n };\n\n /**\n * Init.\n *\n * @param {object} data Data exported from PHP.\n * @returns {void}\n */\n component.init = function init( data ) {\n if ( data ) {\n _.extend( component.data, data );\n }\n api.selectiveRefresh.bind( 'render-partials-response', component.handleRenderPartialsResponse );\n };\n\n /**\n * Handle render-partials-response event, requesting full refresh if newly-enqueued styles/styles differ.\n *\n * @param {object} response Response.\n * @returns {void}\n */\n component.handleRenderPartialsResponse = function handleRenderPartialsResponse( response ) {\n if ( ! response.wpse_247251 ) {\n return;\n }\n if ( ! _.isEqual( component.data.enqueued_styles, response.wpse_247251.enqueued_styles ) ) {\n api.selectiveRefresh.requestFullRefresh();\n }\n if ( ! _.isEqual( component.data.enqueued_scripts, response.wpse_247251.enqueued_scripts ) ) {\n api.selectiveRefresh.requestFullRefresh();\n }\n };\n\n return component;\n})( wp.customize );\n</code></pre>\n\n<p>An inline script can be added in PHP to export the <code>enqueued_scripts</code> and <code>enqueued_styles</code> by then calling <code>WPSE_247251.init( data )</code>.</p>\n\n<p>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 <code>body</code>. 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 <code>partial-content-rendered</code> event triggered on <code>wp.customize.selectiveRefresh</code> to then call that function passing in <code>placement.container</code> as the scope for initializing rather than the entire <code>body</code>:</p>\n\n<pre><code>if ( 'undefined' !== typeof wp && 'undefined' !== typeof wp.customize && 'undefined' !== typeof wp.customize.selectiveRefresh ) {\n wp.customize.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {\n initializeAllElements( $( placement.container ) );\n } );\n}\n</code></pre>\n\n<p>So again, see a <a href=\"https://gist.github.com/westonruter/d4a21d8c891974e808975dcdfe97625d\" rel=\"noreferrer\">standalone example plugin</a> 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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 250200,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>I wold like to add some notes to certain parts of this question.</p>\n\n<p>Mark set a downvote for my <a href=\"https://wordpress.stackexchange.com/questions/236338/react-customizer-api/242863#242863\">answer</a> of injecting React to WordPress. React is present for 5 years now and it is relatively stable. These words in @WestonRuter answer I like the most.</p>\n\n<blockquote>\n <p>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.</p>\n</blockquote>\n\n<p>To get to the stage where we can live preview (in the Preview pane) anything we need capable JavaScript. React looks like a missing part, but we actually need to create settings, controls, sections, and panels live in JavaScript and to update the WordPress manager global, which seems easy.</p>\n\n<p>@WestonRuter may correct me.</p>\n\n<p>The promises:</p>\n\n<ul>\n<li>KISS (keep-it-simple) and </li>\n<li>DRY (do-not-repeat-yourself). </li>\n</ul>\n\n<p>These are from the common sense, but these don't reflect the state we have now. We repeat and must repeat since our models are dual. They exist in both JavaScript and WordPress PHP world.</p>\n\n<p>Here is one section of the PHP classes we have.</p>\n\n<p><a href=\"https://i.stack.imgur.com/PBk5I.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PBk5I.png\" alt=\"enter image description here\"></a></p>\n\n<p>Similar models exist in JavaScrpt at least to hold the data.</p>\n"
}
] |
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 for <code>/</code> in the query.</p>\n\n<pre><code>add_action('pre_get_posts','search_query');\nfunction search_query($query){\n if (!is_admin() && $query->is_main_query() && is_search()){\n $search = $query->query_vars['s'];\n if (strpos('/', $search) !== false){\n // Found '/' in search query\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 247363,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>After the question's update, I think that you need to set the canonical URL:</p>\n\n<pre><code>add_action( 'wp_head', 'cyb_search_results_canonical_URL' );\nfunction cyb_search_results_canonical_URL() {\n if( is_search() ) {\n $link = get_search_link();\n echo '<link rel=\"canonical\" href=\"' . esc_url( $link ) . '\">';\n }\n}\n</code></pre>\n\n<p>And your problem with duplicated content is fixed.</p>\n"
}
] |
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\"><code>register_post_type_args</code></a> filter can be used to modify post type arguments:</p>\n\n<pre><code>add_filter( 'register_post_type_args', 'wpse247328_register_post_type_args', 10, 2 );\nfunction wpse247328_register_post_type_args( $args, $post_type ) {\n\n if ( 'portfolio' === $post_type ) {\n $args['rewrite']['slug'] = 'stories';\n }\n\n return $args;\n}\n</code></pre>\n"
},
{
"answer_id": 270522,
"author": "Felipe Romero",
"author_id": 91557,
"author_profile": "https://wordpress.stackexchange.com/users/91557",
"pm_score": 3,
"selected": false,
"text": "<p>@dave-romsey answer didn't work for me, PHP kept telling me <code>Warning: Cannot use a scalar value as an array in /path/to/functions.php</code>\nSo I went the <code>array_merge</code> way. </p>\n\n<p>Complete function you need to add to your child's theme <code>functions.php</code> file:</p>\n\n<pre><code>function update_portfolios_slug( $args, $post_type ) {\n\n if ( 'portfolios' === $post_type ) {\n\n //$args['rewrite']['slug'] = 'presidentes';\n\n $my_args = array(\n 'rewrite' => array( 'slug' => 'presidentes', 'with_front' => false )\n );\n\n return array_merge( $args, $my_args );\n }\n\n return $args;\n}\n\nadd_filter( 'register_post_type_args', 'update_portfolios_slug', 10, 2 );\n</code></pre>\n\n<p>After uploading your code don't forget to \"refresh\" your Permalinks by going to <strong>Settings > Permalinks</strong> and hitting <em>Save changes</em>.</p>\n\n<p>Cheers. </p>\n"
}
] |
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/[email protected]';
$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 that you can assign as id. This question are a little confusing, can you give me a plain explain about it?</p>\n"
},
{
"answer_id": 247334,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": true,
"text": "<p>Take a look at side loading images. <a href=\"https://codex.wordpress.org/Function_Reference/media_sideload_image\" rel=\"nofollow noreferrer\"><code>media_sideload_image()</code></a>/<a href=\"https://codex.wordpress.org/Function_Reference/wp_handle_sideload\" rel=\"nofollow noreferrer\"><code>wp_handle_sideload()</code></a> and get the ID from the URL. <a href=\"https://developer.wordpress.org/reference/functions/attachment_url_to_postid/\" rel=\"nofollow noreferrer\"><code>attachment_url_to_postid</code></a>.</p>\n\n<pre><code><?php\n\n$url = \"http://wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png\";\n$title = \"Some Image Title\";\n$alt_text = \"Some Alt Text\";\n\nrequire_once(ABSPATH . 'wp-admin/includes/media.php');\nrequire_once(ABSPATH . 'wp-admin/includes/file.php');\nrequire_once(ABSPATH . 'wp-admin/includes/image.php');\n\n// sideload the image --- requires the files above to work correctly\n$src = media_sideload_image( $url, null, null, 'src' );\n\n// convert the url to image id\n$image_id = attachment_url_to_postid( $src );\n\nif( $image_id ) {\n\n // make sure the post exists\n $image = get_post( $image_id );\n\n if( $image) {\n\n // Add title to image\n wp_update_post( array (\n 'ID' => $image->ID,\n 'post_title' => \"Some Image Title\",\n ) );\n\n // Add Alt text to image\n update_post_meta($image->ID, '_wp_attachment_image_alt', $alt_text);\n }\n}\n</code></pre>\n"
}
] |
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/[email protected]';
$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 noreferrer\">The template hierarchy has filters</a> for all types of templates. Here we can use <code>category_template</code>, check if the current category has a parent, and load the <code>subcategory.php</code> file in that case:</p>\n<pre><code>function wpd_subcategory_template( $template ) {\n $cat = get_queried_object();\n if ( isset( $cat ) && $cat->category_parent ) {\n $template = locate_template( 'subcategory.php' );\n }\n\n return $template;\n}\nadd_filter( 'category_template', 'wpd_subcategory_template' );\n</code></pre>\n"
},
{
"answer_id": 270822,
"author": "user3751604",
"author_id": 122263,
"author_profile": "https://wordpress.stackexchange.com/users/122263",
"pm_score": 2,
"selected": false,
"text": "<p>I have edited your code to add more functionality. For cases where someone would want to have a different template for each child category. For example if you have categories ordered like this:</p>\n\n<ul>\n<li>continent\n\n<ul>\n<li>country\n\n<ul>\n<li>city</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>And you need a different template for city. First we look if city has a child, if not we call the template for city. The rest of code is to check if a category has a parent. </p>\n\n<pre><code>// Different template for subcategories\nfunction wpd_subcategory_template( $template ) {\n $cat = get_queried_object();\n $children = get_terms( $cat->taxonomy, array(\n 'parent' => $cat->term_id,\n 'hide_empty' => false\n ) );\n\n if( ! $children ) {\n $template = locate_template( 'category-country-city.php' );\n } elseif( 0 < $cat->category_parent ) {\n $template = locate_template( 'category-country.php' );\n }\n\n return $template;\n}\nadd_filter( 'category_template', 'wpd_subcategory_template' );\n</code></pre>\n"
}
] |
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 the option is not set.</p>\n\n<p>So, if the default value is <code>\"1\"</code>, you can use:</p>\n\n<pre><code>get_theme_mod( 'display_header_image_title', '1' )\n</code></pre>\n\n<p>Then, if there is not value for <code>display_header_image_title</code> (no value in database), <code>\"1\"</code> is used. So, you could check the exact value:</p>\n\n<pre><code>if( get_theme_mod( 'display_header_image_title', '1' ) === '1' ) {\n}\n</code></pre>\n\n<p>Or just true/false:</p>\n\n<pre><code>if( get_theme_mod( 'display_header_image_title', '1' ) ) {\n}\n</code></pre>\n"
},
{
"answer_id": 247377,
"author": "Troy Templeman",
"author_id": 40536,
"author_profile": "https://wordpress.stackexchange.com/users/40536",
"pm_score": 0,
"selected": false,
"text": "<p>Adding a default value fixed it, with the help from @cybmeta. Thanks!</p>\n\n<pre><code><?php if( get_theme_mod( 'display_header_image_title' , '1' ) == '1') { ?>\n</code></pre>\n"
}
] |
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 the option is not set.</p>\n\n<p>So, if the default value is <code>\"1\"</code>, you can use:</p>\n\n<pre><code>get_theme_mod( 'display_header_image_title', '1' )\n</code></pre>\n\n<p>Then, if there is not value for <code>display_header_image_title</code> (no value in database), <code>\"1\"</code> is used. So, you could check the exact value:</p>\n\n<pre><code>if( get_theme_mod( 'display_header_image_title', '1' ) === '1' ) {\n}\n</code></pre>\n\n<p>Or just true/false:</p>\n\n<pre><code>if( get_theme_mod( 'display_header_image_title', '1' ) ) {\n}\n</code></pre>\n"
},
{
"answer_id": 247377,
"author": "Troy Templeman",
"author_id": 40536,
"author_profile": "https://wordpress.stackexchange.com/users/40536",
"pm_score": 0,
"selected": false,
"text": "<p>Adding a default value fixed it, with the help from @cybmeta. Thanks!</p>\n\n<pre><code><?php if( get_theme_mod( 'display_header_image_title' , '1' ) == '1') { ?>\n</code></pre>\n"
}
] |
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 the option is not set.</p>\n\n<p>So, if the default value is <code>\"1\"</code>, you can use:</p>\n\n<pre><code>get_theme_mod( 'display_header_image_title', '1' )\n</code></pre>\n\n<p>Then, if there is not value for <code>display_header_image_title</code> (no value in database), <code>\"1\"</code> is used. So, you could check the exact value:</p>\n\n<pre><code>if( get_theme_mod( 'display_header_image_title', '1' ) === '1' ) {\n}\n</code></pre>\n\n<p>Or just true/false:</p>\n\n<pre><code>if( get_theme_mod( 'display_header_image_title', '1' ) ) {\n}\n</code></pre>\n"
},
{
"answer_id": 247377,
"author": "Troy Templeman",
"author_id": 40536,
"author_profile": "https://wordpress.stackexchange.com/users/40536",
"pm_score": 0,
"selected": false,
"text": "<p>Adding a default value fixed it, with the help from @cybmeta. Thanks!</p>\n\n<pre><code><?php if( get_theme_mod( 'display_header_image_title' , '1' ) == '1') { ?>\n</code></pre>\n"
}
] |
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>You need to change the second instance of:</p>\n\n<pre><code>wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=location' )\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=location&name=location,' )\n</code></pre>\n\n<p>And then change this:\n <code>wp_set_post_terms( $pid, $_POST['cat'], 'location', false );</code></p>\n\n<p>to:\n <code>wp_set_post_terms( $pid, $_POST['location'], 'location', false );</code></p>\n"
},
{
"answer_id": 247470,
"author": "Dipen Desai",
"author_id": 107579,
"author_profile": "https://wordpress.stackexchange.com/users/107579",
"pm_score": 0,
"selected": false,
"text": "<p>try this </p>\n\n<pre><code>//hook into the init action and call create_book_taxonomies when it fires\n add_action( 'init', 'create_topics_hierarchical_taxonomy', 0 );\n\n //create a custom taxonomy name it topics for your posts\n\n function create_topics_hierarchical_taxonomy() {\n\n // Add new taxonomy, make it hierarchical like categories\n //first do the translations part for GUI\n\n $labels = array(\n 'name' => _x( 'Topics', 'taxonomy general name' ),\n 'singular_name' => _x( 'Topic', 'taxonomy singular name' ),\n 'search_items' => __( 'Search Topics' ),\n 'all_items' => __( 'All Topics' ),\n 'parent_item' => __( 'Parent Topic' ),\n 'parent_item_colon' => __( 'Parent Topic:' ),\n 'edit_item' => __( 'Edit Topic' ), \n 'update_item' => __( 'Update Topic' ),\n 'add_new_item' => __( 'Add New Topic' ),\n 'new_item_name' => __( 'New Topic Name' ),\n 'menu_name' => __( 'Topics' ),\n ); \n\n // Now register the taxonomy\n\n register_taxonomy('topics',array('post'), array(\n 'hierarchical' => true,\n 'labels' => $labels,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'topic' ),\n ));\n\n}\n</code></pre>\n"
},
{
"answer_id": 247477,
"author": "C Sabhar",
"author_id": 103830,
"author_profile": "https://wordpress.stackexchange.com/users/103830",
"pm_score": 3,
"selected": true,
"text": "<p><strong>wp_set_post_terms() function will only work on the native post type</strong>.</p>\n\n<p>For a taxonomy on a custom post type use <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">wp_set_object_terms()</a>.</p>\n\n<p>Change your code to:</p>\n\n<pre><code>wp_set_object_terms( $pid, $_POST['cat'], 'books-categories', false );\nwp_set_object_terms( $pid, $_POST['location'], 'location', false );\n</code></pre>\n"
},
{
"answer_id": 288574,
"author": "dipak_pusti",
"author_id": 44528,
"author_profile": "https://wordpress.stackexchange.com/users/44528",
"pm_score": 0,
"selected": false,
"text": "<p><code>wp_set_object_term</code> is the function you need. Please see this page,</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_set_object_terms</a></p>\n\n<pre><code>wp_set_object_terms( $pid, array($_POST['cat']), 'books-categories' );\nwp_set_object_terms( $pid, array($_POST['location']), 'location' );\n</code></pre>\n\n<p>Hope this one helps :)</p>\n"
}
] |
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>You need to change the second instance of:</p>\n\n<pre><code>wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=location' )\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=location&name=location,' )\n</code></pre>\n\n<p>And then change this:\n <code>wp_set_post_terms( $pid, $_POST['cat'], 'location', false );</code></p>\n\n<p>to:\n <code>wp_set_post_terms( $pid, $_POST['location'], 'location', false );</code></p>\n"
},
{
"answer_id": 247470,
"author": "Dipen Desai",
"author_id": 107579,
"author_profile": "https://wordpress.stackexchange.com/users/107579",
"pm_score": 0,
"selected": false,
"text": "<p>try this </p>\n\n<pre><code>//hook into the init action and call create_book_taxonomies when it fires\n add_action( 'init', 'create_topics_hierarchical_taxonomy', 0 );\n\n //create a custom taxonomy name it topics for your posts\n\n function create_topics_hierarchical_taxonomy() {\n\n // Add new taxonomy, make it hierarchical like categories\n //first do the translations part for GUI\n\n $labels = array(\n 'name' => _x( 'Topics', 'taxonomy general name' ),\n 'singular_name' => _x( 'Topic', 'taxonomy singular name' ),\n 'search_items' => __( 'Search Topics' ),\n 'all_items' => __( 'All Topics' ),\n 'parent_item' => __( 'Parent Topic' ),\n 'parent_item_colon' => __( 'Parent Topic:' ),\n 'edit_item' => __( 'Edit Topic' ), \n 'update_item' => __( 'Update Topic' ),\n 'add_new_item' => __( 'Add New Topic' ),\n 'new_item_name' => __( 'New Topic Name' ),\n 'menu_name' => __( 'Topics' ),\n ); \n\n // Now register the taxonomy\n\n register_taxonomy('topics',array('post'), array(\n 'hierarchical' => true,\n 'labels' => $labels,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'topic' ),\n ));\n\n}\n</code></pre>\n"
},
{
"answer_id": 247477,
"author": "C Sabhar",
"author_id": 103830,
"author_profile": "https://wordpress.stackexchange.com/users/103830",
"pm_score": 3,
"selected": true,
"text": "<p><strong>wp_set_post_terms() function will only work on the native post type</strong>.</p>\n\n<p>For a taxonomy on a custom post type use <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">wp_set_object_terms()</a>.</p>\n\n<p>Change your code to:</p>\n\n<pre><code>wp_set_object_terms( $pid, $_POST['cat'], 'books-categories', false );\nwp_set_object_terms( $pid, $_POST['location'], 'location', false );\n</code></pre>\n"
},
{
"answer_id": 288574,
"author": "dipak_pusti",
"author_id": 44528,
"author_profile": "https://wordpress.stackexchange.com/users/44528",
"pm_score": 0,
"selected": false,
"text": "<p><code>wp_set_object_term</code> is the function you need. Please see this page,</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_set_object_terms</a></p>\n\n<pre><code>wp_set_object_terms( $pid, array($_POST['cat']), 'books-categories' );\nwp_set_object_terms( $pid, array($_POST['location']), 'location' );\n</code></pre>\n\n<p>Hope this one helps :)</p>\n"
}
] |
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/themes/basics/template-hierarchy/\" rel=\"nofollow\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></p>\n"
},
{
"answer_id": 247440,
"author": "Beee",
"author_id": 103402,
"author_profile": "https://wordpress.stackexchange.com/users/103402",
"pm_score": 2,
"selected": true,
"text": "<p>First plugins are loaded, then templates.</p>\n\n<p>Media is not loaded until called (afaik) from either a plugin or theme.</p>\n\n<p>Widgets, enqueued scripts and CSS can be called from both plugins and templates so it depends where they are defined.</p>\n"
}
] |
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 save_ispublished( $post_id ) {\n\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)\n return;\n\n $published_once = get_post_meta( $post_id, 'is_published', true );\n\n // Check if 'is_published' meta value is empty.\n if ( ! empty( $published_once ) ) {\n\n $published_once = 'yes';\n }\n\n // store is_published value when first time published.\n update_post_meta( $post_id, 'is_published', $published_once );\n}\nadd_action( 'save_post', 'save_ispublished' );\n</code></pre>\n\n<p>you can check it by get the meta value.</p>\n\n<pre><code>$is_published = get_post_meta( $post_id, 'is_published', true );\n\nif( $is_published == 'yes' ) {\n\n /*\n * Actions if post is already published atleast once.\n */\n}\n</code></pre>\n\n<p>Hope this help ! </p>\n"
},
{
"answer_id": 247490,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>I totally agree with @Govind Kumar except for the action uses in the example, you can use <code>publish_post</code> action instead of <code>save_post</code>.</p>\n\n<p><code>publish_post</code> is an action triggered whenever a post is published, or if it is edited and the status is changed to publish. Save_post will trigger each time the post is save.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow\">publish_post action</a></p>\n"
}
] |
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 save_ispublished( $post_id ) {\n\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)\n return;\n\n $published_once = get_post_meta( $post_id, 'is_published', true );\n\n // Check if 'is_published' meta value is empty.\n if ( ! empty( $published_once ) ) {\n\n $published_once = 'yes';\n }\n\n // store is_published value when first time published.\n update_post_meta( $post_id, 'is_published', $published_once );\n}\nadd_action( 'save_post', 'save_ispublished' );\n</code></pre>\n\n<p>you can check it by get the meta value.</p>\n\n<pre><code>$is_published = get_post_meta( $post_id, 'is_published', true );\n\nif( $is_published == 'yes' ) {\n\n /*\n * Actions if post is already published atleast once.\n */\n}\n</code></pre>\n\n<p>Hope this help ! </p>\n"
},
{
"answer_id": 247490,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>I totally agree with @Govind Kumar except for the action uses in the example, you can use <code>publish_post</code> action instead of <code>save_post</code>.</p>\n\n<p><code>publish_post</code> is an action triggered whenever a post is published, or if it is edited and the status is changed to publish. Save_post will trigger each time the post is save.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow\">publish_post action</a></p>\n"
}
] |
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 save_ispublished( $post_id ) {\n\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)\n return;\n\n $published_once = get_post_meta( $post_id, 'is_published', true );\n\n // Check if 'is_published' meta value is empty.\n if ( ! empty( $published_once ) ) {\n\n $published_once = 'yes';\n }\n\n // store is_published value when first time published.\n update_post_meta( $post_id, 'is_published', $published_once );\n}\nadd_action( 'save_post', 'save_ispublished' );\n</code></pre>\n\n<p>you can check it by get the meta value.</p>\n\n<pre><code>$is_published = get_post_meta( $post_id, 'is_published', true );\n\nif( $is_published == 'yes' ) {\n\n /*\n * Actions if post is already published atleast once.\n */\n}\n</code></pre>\n\n<p>Hope this help ! </p>\n"
},
{
"answer_id": 247490,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>I totally agree with @Govind Kumar except for the action uses in the example, you can use <code>publish_post</code> action instead of <code>save_post</code>.</p>\n\n<p><code>publish_post</code> is an action triggered whenever a post is published, or if it is edited and the status is changed to publish. Save_post will trigger each time the post is save.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow\">publish_post action</a></p>\n"
}
] |
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 leave some po/mo files in the <code>wp-content/languages/woocommerce-multilingual/</code> or wpml one.\nI found on a <a href=\"https://wpml.org/forums/topic/how-to-get-wpml-to-use-mo-files/\" rel=\"nofollow noreferrer\">thread</a> saying</p>\n\n<blockquote>\n <ol>\n <li>Visit WPML > Theme and plugin localization > select 'Translate using .mo files' > select Automatically load the theme's .mo file\n using 'load_theme_textdomain'. > Enter textdomain > Save</li>\n <li>The translations for wordpress and the admin screen are those to be placed in wp-content/languages - Download these files here:\n <a href=\"http://wpcentral.io/internationalization/\" rel=\"nofollow noreferrer\">http://wpcentral.io/internationalization/</a></li>\n <li>Your theme's language should be put in a themes/awr-theme/languages/ directory</li>\n <li>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\n locale setting, WPML is associating es_ES.mo. You can review those\n options if you visit WPML > Languages > Site Languages > Edit\n Languages.</li>\n </ol>\n</blockquote>\n\n<p>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.</p>\n\n<p>Depending on how you deactivate (and delete ?) the plugin, is it possible that some options settings of multi-currency plugins remains in your install ?</p>\n\n<p>Are you sure that any code (yours or another plugin or theme) is not calling <code>class-wcml-bookings.php</code> 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.</p>\n\n<p>In case I'm wrong, about the filter you are talking about line 163</p>\n\n<pre><code>add_filter( 'get_post_metadata', array( $this, 'filter_wc_booking_cost' ), 10, 4 );\n</code></pre>\n\n<p>Did you try to remove it with <code>remove_filter()</code> ?</p>\n\n<pre><code>remove_filter('get_post_metadata', 10, 4);\n</code></pre>\n\n<p>Writing this I lean more on mo/po way than filter. </p>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 248204,
"author": "Daniel Mulder",
"author_id": 86859,
"author_profile": "https://wordpress.stackexchange.com/users/86859",
"pm_score": 0,
"selected": false,
"text": "<p>Before you wreck your self check your WC settings -> tools page and first try to clear all trancients and do recount of terms. WC uses trancients and these need to be cleared some times. </p>\n"
}
] |
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 executing the php code they contain.</p>\n"
},
{
"answer_id": 248170,
"author": "Scotty Jakes",
"author_id": 107811,
"author_profile": "https://wordpress.stackexchange.com/users/107811",
"pm_score": 0,
"selected": false,
"text": "<p>The reason for using headers placed within comments is it gives WordPress core and WordPress libraries for themes and plugins a way read data they need in a secure and simple way. Alternatives, such as putting the data in configuration files, are seen as either more complicated, less secure or both. The WordPress development team puts more weight on \"simple and secure\" than on keeping required elements out of the comments within files. </p>\n"
}
] |
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()</code>, and it returns null. In a function, external data must be provide via the function parameters <code>output_my_custom_field($post)</code> or set with global <code>global $post</code> .</p>\n\n<p>When using <code>the_post</code> action, you need to add <code>$post_object</code> parameter to the function. <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/the_post\" rel=\"nofollow noreferrer\">See <code>the_post</code> example</a></p>\n\n<p><strong><code>the_post</code> is only use Iterate the post index in the loop.</strong> If you want to display a custom field value, you can use <code>the_content</code> or create a shortcode. </p>\n\n<p>A simple to return the custom .field before the content.</p>\n\n<pre><code>add_filter( 'the_content', 'output_my_custom_field');\n\nfunction output_my_custom_field($content) {\n\n global $post; \n\n $post_id = $post->ID;\n $post_title = $post->post_title;\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n $content = $my_custom_field . $content;\n } \n return $content;\n}\n</code></pre>\n\n<p>If you want to use template tag in your function, your need to add <code>setup_postdata( $post );</code> .</p>\n\n<pre><code> add_filter( 'the_content', 'output_my_custom_field');\n\n function output_my_custom_field($content) {\n global $post;\n setup_postdata($post);\n\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n wp_reset_postdata();\n } \n return $content;\n }\n</code></pre>\n\n<p>In your case there's no need to reset the post data with <code>wp_reset_postdata()</code>, because this function restore the original query (and your running on the same one).</p>\n\n<p>Hope it helps to make it work !</p>\n"
},
{
"answer_id": 248277,
"author": "Jorge Raigoza",
"author_id": 74600,
"author_profile": "https://wordpress.stackexchange.com/users/74600",
"pm_score": 0,
"selected": false,
"text": "<p>This is more of a comment than an answer, but I can't \"comment\".</p>\n\n<p>Have you checked the posts that you're trying to retrieve this information from? </p>\n\n<p>Are the posts marked as private (admin only) or not published? </p>\n\n<p>Try creating another WordPress account with limited access (but higher rights than a regular user) and see if it works.</p>\n"
},
{
"answer_id": 248278,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Not 100% sure I understand the question or problem, but this ought to work, I think:</p>\n\n<pre><code>add_action( 'the_post', 'output_my_custom_field');\n\nfunction output_my_custom_field( $post_object ) {\n\n $post_id = $post_object->ID;\n\n // why the conditional (and redundant !empty) ?\n // if ( !empty($post_id) ) ) { \n\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n // see above\n // } \n\n }\n</code></pre>\n"
},
{
"answer_id": 248463,
"author": "Varun Kumar",
"author_id": 103095,
"author_profile": "https://wordpress.stackexchange.com/users/103095",
"pm_score": 0,
"selected": false,
"text": "<p>It's just the hook issue you are using 'the_post', try an other one which suits here, like I just tried using 'init' and its working just fine.</p>\n\n<pre><code>add_action( 'init', 'output_my_custom_field');\nfunction output_my_custom_field() {\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 248497,
"author": "WraithKenny",
"author_id": 279,
"author_profile": "https://wordpress.stackexchange.com/users/279",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>$my_custom_field = get_post_meta( $post_id, 'my_custom_field', false );\nvar_dump($my_custom_field);\n</code></pre>\n\n<p>It could be that you created the meta field with the wrong version of <code>add_post_meta( $post_id, 'my_custom_field', 'IT works!', false )</code></p>\n"
}
] |
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()</code>, and it returns null. In a function, external data must be provide via the function parameters <code>output_my_custom_field($post)</code> or set with global <code>global $post</code> .</p>\n\n<p>When using <code>the_post</code> action, you need to add <code>$post_object</code> parameter to the function. <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/the_post\" rel=\"nofollow noreferrer\">See <code>the_post</code> example</a></p>\n\n<p><strong><code>the_post</code> is only use Iterate the post index in the loop.</strong> If you want to display a custom field value, you can use <code>the_content</code> or create a shortcode. </p>\n\n<p>A simple to return the custom .field before the content.</p>\n\n<pre><code>add_filter( 'the_content', 'output_my_custom_field');\n\nfunction output_my_custom_field($content) {\n\n global $post; \n\n $post_id = $post->ID;\n $post_title = $post->post_title;\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n $content = $my_custom_field . $content;\n } \n return $content;\n}\n</code></pre>\n\n<p>If you want to use template tag in your function, your need to add <code>setup_postdata( $post );</code> .</p>\n\n<pre><code> add_filter( 'the_content', 'output_my_custom_field');\n\n function output_my_custom_field($content) {\n global $post;\n setup_postdata($post);\n\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n wp_reset_postdata();\n } \n return $content;\n }\n</code></pre>\n\n<p>In your case there's no need to reset the post data with <code>wp_reset_postdata()</code>, because this function restore the original query (and your running on the same one).</p>\n\n<p>Hope it helps to make it work !</p>\n"
},
{
"answer_id": 248277,
"author": "Jorge Raigoza",
"author_id": 74600,
"author_profile": "https://wordpress.stackexchange.com/users/74600",
"pm_score": 0,
"selected": false,
"text": "<p>This is more of a comment than an answer, but I can't \"comment\".</p>\n\n<p>Have you checked the posts that you're trying to retrieve this information from? </p>\n\n<p>Are the posts marked as private (admin only) or not published? </p>\n\n<p>Try creating another WordPress account with limited access (but higher rights than a regular user) and see if it works.</p>\n"
},
{
"answer_id": 248278,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Not 100% sure I understand the question or problem, but this ought to work, I think:</p>\n\n<pre><code>add_action( 'the_post', 'output_my_custom_field');\n\nfunction output_my_custom_field( $post_object ) {\n\n $post_id = $post_object->ID;\n\n // why the conditional (and redundant !empty) ?\n // if ( !empty($post_id) ) ) { \n\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n // see above\n // } \n\n }\n</code></pre>\n"
},
{
"answer_id": 248463,
"author": "Varun Kumar",
"author_id": 103095,
"author_profile": "https://wordpress.stackexchange.com/users/103095",
"pm_score": 0,
"selected": false,
"text": "<p>It's just the hook issue you are using 'the_post', try an other one which suits here, like I just tried using 'init' and its working just fine.</p>\n\n<pre><code>add_action( 'init', 'output_my_custom_field');\nfunction output_my_custom_field() {\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 248497,
"author": "WraithKenny",
"author_id": 279,
"author_profile": "https://wordpress.stackexchange.com/users/279",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>$my_custom_field = get_post_meta( $post_id, 'my_custom_field', false );\nvar_dump($my_custom_field);\n</code></pre>\n\n<p>It could be that you created the meta field with the wrong version of <code>add_post_meta( $post_id, 'my_custom_field', 'IT works!', false )</code></p>\n"
}
] |
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()</code>, and it returns null. In a function, external data must be provide via the function parameters <code>output_my_custom_field($post)</code> or set with global <code>global $post</code> .</p>\n\n<p>When using <code>the_post</code> action, you need to add <code>$post_object</code> parameter to the function. <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/the_post\" rel=\"nofollow noreferrer\">See <code>the_post</code> example</a></p>\n\n<p><strong><code>the_post</code> is only use Iterate the post index in the loop.</strong> If you want to display a custom field value, you can use <code>the_content</code> or create a shortcode. </p>\n\n<p>A simple to return the custom .field before the content.</p>\n\n<pre><code>add_filter( 'the_content', 'output_my_custom_field');\n\nfunction output_my_custom_field($content) {\n\n global $post; \n\n $post_id = $post->ID;\n $post_title = $post->post_title;\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n $content = $my_custom_field . $content;\n } \n return $content;\n}\n</code></pre>\n\n<p>If you want to use template tag in your function, your need to add <code>setup_postdata( $post );</code> .</p>\n\n<pre><code> add_filter( 'the_content', 'output_my_custom_field');\n\n function output_my_custom_field($content) {\n global $post;\n setup_postdata($post);\n\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n wp_reset_postdata();\n } \n return $content;\n }\n</code></pre>\n\n<p>In your case there's no need to reset the post data with <code>wp_reset_postdata()</code>, because this function restore the original query (and your running on the same one).</p>\n\n<p>Hope it helps to make it work !</p>\n"
},
{
"answer_id": 248277,
"author": "Jorge Raigoza",
"author_id": 74600,
"author_profile": "https://wordpress.stackexchange.com/users/74600",
"pm_score": 0,
"selected": false,
"text": "<p>This is more of a comment than an answer, but I can't \"comment\".</p>\n\n<p>Have you checked the posts that you're trying to retrieve this information from? </p>\n\n<p>Are the posts marked as private (admin only) or not published? </p>\n\n<p>Try creating another WordPress account with limited access (but higher rights than a regular user) and see if it works.</p>\n"
},
{
"answer_id": 248278,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Not 100% sure I understand the question or problem, but this ought to work, I think:</p>\n\n<pre><code>add_action( 'the_post', 'output_my_custom_field');\n\nfunction output_my_custom_field( $post_object ) {\n\n $post_id = $post_object->ID;\n\n // why the conditional (and redundant !empty) ?\n // if ( !empty($post_id) ) ) { \n\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n // see above\n // } \n\n }\n</code></pre>\n"
},
{
"answer_id": 248463,
"author": "Varun Kumar",
"author_id": 103095,
"author_profile": "https://wordpress.stackexchange.com/users/103095",
"pm_score": 0,
"selected": false,
"text": "<p>It's just the hook issue you are using 'the_post', try an other one which suits here, like I just tried using 'init' and its working just fine.</p>\n\n<pre><code>add_action( 'init', 'output_my_custom_field');\nfunction output_my_custom_field() {\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 248497,
"author": "WraithKenny",
"author_id": 279,
"author_profile": "https://wordpress.stackexchange.com/users/279",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>$my_custom_field = get_post_meta( $post_id, 'my_custom_field', false );\nvar_dump($my_custom_field);\n</code></pre>\n\n<p>It could be that you created the meta field with the wrong version of <code>add_post_meta( $post_id, 'my_custom_field', 'IT works!', false )</code></p>\n"
}
] |
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()</code>, and it returns null. In a function, external data must be provide via the function parameters <code>output_my_custom_field($post)</code> or set with global <code>global $post</code> .</p>\n\n<p>When using <code>the_post</code> action, you need to add <code>$post_object</code> parameter to the function. <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/the_post\" rel=\"nofollow noreferrer\">See <code>the_post</code> example</a></p>\n\n<p><strong><code>the_post</code> is only use Iterate the post index in the loop.</strong> If you want to display a custom field value, you can use <code>the_content</code> or create a shortcode. </p>\n\n<p>A simple to return the custom .field before the content.</p>\n\n<pre><code>add_filter( 'the_content', 'output_my_custom_field');\n\nfunction output_my_custom_field($content) {\n\n global $post; \n\n $post_id = $post->ID;\n $post_title = $post->post_title;\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n $content = $my_custom_field . $content;\n } \n return $content;\n}\n</code></pre>\n\n<p>If you want to use template tag in your function, your need to add <code>setup_postdata( $post );</code> .</p>\n\n<pre><code> add_filter( 'the_content', 'output_my_custom_field');\n\n function output_my_custom_field($content) {\n global $post;\n setup_postdata($post);\n\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n wp_reset_postdata();\n } \n return $content;\n }\n</code></pre>\n\n<p>In your case there's no need to reset the post data with <code>wp_reset_postdata()</code>, because this function restore the original query (and your running on the same one).</p>\n\n<p>Hope it helps to make it work !</p>\n"
},
{
"answer_id": 248277,
"author": "Jorge Raigoza",
"author_id": 74600,
"author_profile": "https://wordpress.stackexchange.com/users/74600",
"pm_score": 0,
"selected": false,
"text": "<p>This is more of a comment than an answer, but I can't \"comment\".</p>\n\n<p>Have you checked the posts that you're trying to retrieve this information from? </p>\n\n<p>Are the posts marked as private (admin only) or not published? </p>\n\n<p>Try creating another WordPress account with limited access (but higher rights than a regular user) and see if it works.</p>\n"
},
{
"answer_id": 248278,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Not 100% sure I understand the question or problem, but this ought to work, I think:</p>\n\n<pre><code>add_action( 'the_post', 'output_my_custom_field');\n\nfunction output_my_custom_field( $post_object ) {\n\n $post_id = $post_object->ID;\n\n // why the conditional (and redundant !empty) ?\n // if ( !empty($post_id) ) ) { \n\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n // see above\n // } \n\n }\n</code></pre>\n"
},
{
"answer_id": 248463,
"author": "Varun Kumar",
"author_id": 103095,
"author_profile": "https://wordpress.stackexchange.com/users/103095",
"pm_score": 0,
"selected": false,
"text": "<p>It's just the hook issue you are using 'the_post', try an other one which suits here, like I just tried using 'init' and its working just fine.</p>\n\n<pre><code>add_action( 'init', 'output_my_custom_field');\nfunction output_my_custom_field() {\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 248497,
"author": "WraithKenny",
"author_id": 279,
"author_profile": "https://wordpress.stackexchange.com/users/279",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>$my_custom_field = get_post_meta( $post_id, 'my_custom_field', false );\nvar_dump($my_custom_field);\n</code></pre>\n\n<p>It could be that you created the meta field with the wrong version of <code>add_post_meta( $post_id, 'my_custom_field', 'IT works!', false )</code></p>\n"
}
] |
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()</code>, and it returns null. In a function, external data must be provide via the function parameters <code>output_my_custom_field($post)</code> or set with global <code>global $post</code> .</p>\n\n<p>When using <code>the_post</code> action, you need to add <code>$post_object</code> parameter to the function. <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/the_post\" rel=\"nofollow noreferrer\">See <code>the_post</code> example</a></p>\n\n<p><strong><code>the_post</code> is only use Iterate the post index in the loop.</strong> If you want to display a custom field value, you can use <code>the_content</code> or create a shortcode. </p>\n\n<p>A simple to return the custom .field before the content.</p>\n\n<pre><code>add_filter( 'the_content', 'output_my_custom_field');\n\nfunction output_my_custom_field($content) {\n\n global $post; \n\n $post_id = $post->ID;\n $post_title = $post->post_title;\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n $content = $my_custom_field . $content;\n } \n return $content;\n}\n</code></pre>\n\n<p>If you want to use template tag in your function, your need to add <code>setup_postdata( $post );</code> .</p>\n\n<pre><code> add_filter( 'the_content', 'output_my_custom_field');\n\n function output_my_custom_field($content) {\n global $post;\n setup_postdata($post);\n\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n wp_reset_postdata();\n } \n return $content;\n }\n</code></pre>\n\n<p>In your case there's no need to reset the post data with <code>wp_reset_postdata()</code>, because this function restore the original query (and your running on the same one).</p>\n\n<p>Hope it helps to make it work !</p>\n"
},
{
"answer_id": 248277,
"author": "Jorge Raigoza",
"author_id": 74600,
"author_profile": "https://wordpress.stackexchange.com/users/74600",
"pm_score": 0,
"selected": false,
"text": "<p>This is more of a comment than an answer, but I can't \"comment\".</p>\n\n<p>Have you checked the posts that you're trying to retrieve this information from? </p>\n\n<p>Are the posts marked as private (admin only) or not published? </p>\n\n<p>Try creating another WordPress account with limited access (but higher rights than a regular user) and see if it works.</p>\n"
},
{
"answer_id": 248278,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Not 100% sure I understand the question or problem, but this ought to work, I think:</p>\n\n<pre><code>add_action( 'the_post', 'output_my_custom_field');\n\nfunction output_my_custom_field( $post_object ) {\n\n $post_id = $post_object->ID;\n\n // why the conditional (and redundant !empty) ?\n // if ( !empty($post_id) ) ) { \n\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n\n // see above\n // } \n\n }\n</code></pre>\n"
},
{
"answer_id": 248463,
"author": "Varun Kumar",
"author_id": 103095,
"author_profile": "https://wordpress.stackexchange.com/users/103095",
"pm_score": 0,
"selected": false,
"text": "<p>It's just the hook issue you are using 'the_post', try an other one which suits here, like I just tried using 'init' and its working just fine.</p>\n\n<pre><code>add_action( 'init', 'output_my_custom_field');\nfunction output_my_custom_field() {\n $post_id = get_the_ID();\n\n if ( !empty( $post_id ) ) {\n $my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );\n\n var_dump($my_custom_field);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 248497,
"author": "WraithKenny",
"author_id": 279,
"author_profile": "https://wordpress.stackexchange.com/users/279",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>$my_custom_field = get_post_meta( $post_id, 'my_custom_field', false );\nvar_dump($my_custom_field);\n</code></pre>\n\n<p>It could be that you created the meta field with the wrong version of <code>add_post_meta( $post_id, 'my_custom_field', 'IT works!', false )</code></p>\n"
}
] |
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 in that script:</p>\n<pre><code>include(locate_template('include-modal-video.php'));\n</code></pre>\n<p>Then, <code><h2>00: <?php echo $video; ?></h2></code> will work.</p>\n<p><strong>UPDATE:</strong></p>\n<p>Since WP version 5.5, you can pass arbitrary data to <code>get_template_part()</code> for use in the template - see the other answer below from @Denis Fedorov</p>\n"
},
{
"answer_id": 373881,
"author": "Denis Fedorov",
"author_id": 193742,
"author_profile": "https://wordpress.stackexchange.com/users/193742",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Wordpress 5.5</strong></p>\n<p>The <strong>$args</strong> parameter was added to <code>get_template_part</code> function.\n<a href=\"https://developer.wordpress.org/reference/functions/get_template_part/#changelog\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_template_part/#changelog</a></p>\n<p><strong>Pass data</strong></p>\n<pre><code>$data = [\n 'video' => 'video-' . $post->ID,\n];\nget_template_part('include', 'modal-video', $data);\n</code></pre>\n<p><strong>include-modal-video.php</strong></p>\n<pre><code>//handle passed arguments through $args\necho $args['video'];\n</code></pre>\n<p><strong>include-modal-video.php (extract)</strong></p>\n<pre><code>extract($args);\necho $video;\n</code></pre>\n<p>The possibility of passing additional arguments to the template was added to all the template functions that use <code>locate_template</code> in Wordpress 5.5:</p>\n<p><code>get_header</code>, <code>get_footer</code>, <code>get_sidebar</code>, <code>get_template_part</code>.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_header/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_header/</a>\n<a href=\"https://developer.wordpress.org/reference/functions/get_footer/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_footer/</a>\n<a href=\"https://developer.wordpress.org/reference/functions/get_sidebar/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_sidebar/</a>\n<a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_template_part/</a></p>\n"
}
] |
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 accomplish it with a simple form with hidden inputs.</p>\n\n<pre><code><form role=\"search\" method=\"get\" action=\"<?php echo $_SERVER['REQUEST_URI']; ?>\">\n <input type=\"hidden\" name=\"action\" value=\"careers_search\">\n <input type=\"text\" name=\"search-career\" value=\"Search...\">\n <input type=\"submit\" class=\"form-submit\" value=\"Submit\">\n</form>\n</code></pre>\n\n<p>This form will submit itself on the same URL.\nAfter submissions this is what supposed to happen-</p>\n\n<pre><code><?php\n if( isset( $_GET['careers_search'] ) ) {\n // Your code goes here...\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 267751,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>To create your own independent search functionality, follow these steps.</p>\n\n<p><strong>1-</strong> You need a form to send the data for you. This is a simple form that can do this for you:</p>\n\n<pre><code><form method=\"post\" name=\"car-select\" action=\"<?php echo site_url('/my-page/'); ?>\">\n <select name=\"make\">\n <option value=\"benz\">Benz</option>\n <option value=\"bmw\">BMW</option>\n <option value=\"audi\">Audi</option>\n </select>\n <select name=\"type\">\n <option value=\"sedan\">Sedan</option>\n <option value=\"coupe\">Coupe</option>\n </select>\n <input type=\"submit\" value=\"Find my dream car!\"/>\n</form>\n</code></pre>\n\n<p>Which <code>/my-page/</code> is the slug for the page we are going to create later.</p>\n\n<p><strong>2-</strong> A function to handle the search results. Take a look at this basic function that searches the cars based on the entered values:</p>\n\n<pre><code>function my_custom_search() {\n $car_make = $_POST['make'];\n $car_type = $_POST['type'];\n $car_query = new WP_Query ( array (\n 'post_type' => 'post',\n 'tax_query' => array(\n 'relation' => 'AND',\n array (\n 'taxonomy' => 'car_make',\n 'field' => 'slug',\n 'terms' => $car_make,\n ),\n array (\n 'taxonomy' => 'car_type',\n 'field' => 'slug',\n 'terms' => $car_type,\n ),\n ),\n ));\n if ($car_query->have_posts) {\n while($car_query->have_posts()){\n $car_query->the_post();\n get_template_part('WHATEVER TEMPLATE YOU WANT TO USE');\n }\n }\n // Pagination goes here\n}\n</code></pre>\n\n<p><strong>3-</strong> 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 <code>page-my-search-template.php</code>. Then include this function in your new page template, wherever you wish:</p>\n\n<p><code>my_custom_search();</code></p>\n\n<p>You should then create a page with <code>my-page</code> slug (the one in the form's action), using the template you just made.</p>\n\n<p>Now, every submission of the form will trigger a search query and display the results in your very own search template!</p>\n\n<p><strong>WAIT !! I want my pagination !!</strong></p>\n\n<p>You can implement your own pagination in the search function, however i recommend using <a href=\"https://wordpress.org/plugins/wp-pagenavi/\" rel=\"nofollow noreferrer\">WP-PageNavi</a> for those who don't have enough skill to write a pagination script. Install the plugin, and set the query like this:</p>\n\n<p><code>wp_pagenavi(array( 'query' => $car_query ));</code></p>\n\n<p>This way you have a pagination for your custom search page, nice and easy.</p>\n"
}
] |
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 numerically. PHP can do this for you. Let's say you have an array of categories, ordered randomly, like this: </p>\n\n<pre><code>$cats = array ('3', '22', '17', ... '7');\n</code></pre>\n\n<p>You can then use <a href=\"http://php.net/manual/en/function.sort.php\" rel=\"nofollow noreferrer\">PHP sort</a> while forcing a numerical sorting order:</p>\n\n<pre><code>sort ($cats, SORT_NUMERIC);\n</code></pre>\n\n<p>That should give you </p>\n\n<pre><code>$cats = array ('1', '2', '3', ... '25');\n</code></pre>\n"
},
{
"answer_id": 247691,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Based on the research I've done on this, using term meta data is a better all around approach to ordering terms.</p>\n\n<p>However, I was able come up with this snippet which does sort the terms by their name, numerically:</p>\n\n<pre><code>add_filter( 'terms_clauses', 'wpse247680_terms_clauses', 10, 3 );\nfunction wpse247680_terms_clauses( $pieces, $taxonomies, $args ) {\n // Bail if we are not looking at the right taxonomy, 'category' in this case.\n if ( ! in_array( 'category', $taxonomies ) ) {\n return $pieces;\n }\n\n // Casts the term name to an integer\n // Idea derrived from similar idea using posts here: https://www.fldtrace.com/custom-post-types-numeric-title-order\n $pieces['orderby'] = 'ORDER BY (t.name+0) ';\n\n return $pieces;\n} \n</code></pre>\n\n<p>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.\n<a href=\"https://i.stack.imgur.com/GHZfc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GHZfc.png\" alt=\"sort terms numerically by name\"></a></p>\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 $the_month = get_the_time( 'Ym' ); // e.g. 201611\n\n if ( $last_month !== $the_month ) {\n if ( $last_month !== null ) {\n // Close previously opened <div class=\"row\" />\n echo '</div>';\n }\n\n echo '<div class=\"row\">';\n }\n\n $last_month = $the_month;\n\n ?>\n\n <div class=\"col-3\">\n <?php the_title(); ?>\n </div>\n\n <?php\n\n if ( $the_query->current_post + 1 === $the_query->post_count ) {\n // Last item, always close the div\n echo '</div>';\n }\n\nendwhile;\n</code></pre>\n"
},
{
"answer_id": 247816,
"author": "th3rion",
"author_id": 40822,
"author_profile": "https://wordpress.stackexchange.com/users/40822",
"pm_score": 0,
"selected": false,
"text": "<p>@TheDeadMedic Thank you for your help. Code works of course. I wanted also to style first group differently so I added post count. Heres full code:</p>\n\n<pre><code><?php\n\n $args = array(\n 'post_type' => 'post',\n 'posts_per_page' => -1,\n 'order' => 'DESC'\n );\n\n $the_query = new WP_Query($args);\n if ($the_query->have_posts()) : \n\n $last_month = null;\n $postCount = 1;\n\n while ( $the_query->have_posts() ) : $postCount++;\n $the_query->the_post();\n $the_month = get_the_time( 'Ym' ); \n\n if ( $last_month !== $the_month ) {\n if ( $last_month !== null ) {\n\n echo '</div>';\n }\n\n?> \n\n<?php if($postCount == 2) { ?>\n\n <div class=\"firstgroup\"> // style first group of posts\n\n<?php } else { ?>\n\n <div class=\"othergroups\"> // style other groups of posts\n\n<?php } ?>\n\n<?php \n\n }\n\n $last_month = $the_month;\n\n ?>\n\n <div>\n\n <?php the_title(); ?>\n\n </div>\n\n <?php\n\n if ( $the_query->current_post + 1 === $the_query->post_count ) {\n // Last item, always close the div\n echo '</div>';\n }\n\n endwhile;\n\n endif;\n\n wp_reset_postdata();\n\n?>\n</code></pre>\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 font stack includes the following:</p>\n \n <ul>\n <li>-apple-system for Safari (iOS & macOS) and Firefox macOS</li>\n <li>BlinkMacSystemFont for Chrome macOS</li>\n <li>Segoe UI for Windows</li>\n <li>Roboto for Android and Chrome OS</li>\n <li>Oxygen-Sans for KDE</li>\n <li>Ubuntu for Ubuntu</li>\n <li>Cantarell for GNOME</li>\n <li>Helvetica Neue for versions of macOS prior to 10.11</li>\n <li>sans-serif, the standard fallback</li>\n </ul>\n \n <p><a href=\"https://make.wordpress.org/core/2016/07/07/native-fonts-in-4-6/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2016/07/07/native-fonts-in-4-6/</a></p>\n</blockquote>\n\n<p>And exact technical expression/order in CSS as of right now is:</p>\n\n<pre><code>font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen-Sans, Ubuntu, Cantarell, \"Helvetica Neue\", sans-serif;\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 247701,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress uses system fonts as of <a href=\"https://make.wordpress.org/core/2016/07/07/native-fonts-in-4-6/\" rel=\"nofollow noreferrer\">version 4.6</a>.</p>\n\n<p>You can determine the font used by inspecting the element in Chrome Developer Tools or any modern browser's equivalent:</p>\n\n<pre><code>font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen-Sans, Ubuntu, Cantarell, \"Helvetica Neue\", sans-serif\n</code></pre>\n"
}
] |
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_enqueue_style/\" rel=\"noreferrer\"><code>wp_enqueue_style()</code></a> allows you to set the version:</p>\n\n<pre><code>wp_enqueue_style( string $handle,\n string $src = false,\n array $deps = array(),\n string|bool|null $ver = false,\n string $media = 'all' );\n</code></pre>\n\n<p>Per the docs:</p>\n\n<blockquote>\n <p><strong>$ver</strong> (string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query\n string for cache busting purposes. If version is set to false, a\n version number is automatically added equal to current installed\n WordPress version. If set to null, no version is added. Default value:\n <code>false</code></p>\n</blockquote>\n"
},
{
"answer_id": 247965,
"author": "Waqas Jawed",
"author_id": 108039,
"author_profile": "https://wordpress.stackexchange.com/users/108039",
"pm_score": 3,
"selected": false,
"text": "<p>Mostly theme's use <code>wp_enqueue_style()</code> function inside their functions.php file to add style sheet in the header. Here is how to find out if your theme does the same.</p>\n\n<p>Open your <code>wp-content/themes/YOUR_THEME_NAME/functions.php</code> file, and find out the line which is adding the style sheet, Like:</p>\n\n<pre><code>wp_enqueue_style('main_style', get_stylesheet_directory_uri() . '/style.css');\n</code></pre>\n\n<p>Or Like:</p>\n\n<pre><code>wp_enqueue_style( 'twentysixteen-style', get_stylesheet_uri() );\n</code></pre>\n\n<blockquote>\n <p>You can search for the ID (except for <code>-css</code> part)... if the ID is: <code>main_style-css</code> search for just <code>main-style</code> in your functions.php file, and you should probably find the line of code you were looking for.</p>\n</blockquote>\n\n<p>Now that you found the code and you know that your theme adds this stylesheet by using <code>wp_enqueue_style()</code> in functions.php file. You need to update this code for version.</p>\n\n<pre><code>$style_ver = filemtime( get_stylesheet_directory() . '/style.css' );\nwp_enqueue_style( 'main_style', get_stylesheet_directory_uri() . '/style.css', '', $style_ver );\n</code></pre>\n\n<p>As you can see, this code gets the last modified time of style.css file using <code>filemtime()</code> PHP function and it also converts the time to timestamp using <code>time()</code> PHP function just to make things clean.</p>\n\n<p>If you don't want the version to dynamically change every time you can simply do this:</p>\n\n<pre><code>wp_enqueue_style( 'main_style', get_stylesheet_directory_uri() . '/style.css', '', '1.5' );\n</code></pre>\n\n<p>Thats pretty much it. Peace!</p>\n"
},
{
"answer_id": 275329,
"author": "Ben Racicot",
"author_id": 18726,
"author_profile": "https://wordpress.stackexchange.com/users/18726",
"pm_score": 2,
"selected": false,
"text": "<p>I didn't get much out of these answers so I thought I'd write what worked for me. I know the codex says:</p>\n\n<blockquote>\n <p>$ver (string|bool|null) (Optional) String specifying stylesheet\n version number, if it has one, which is added to the URL as a query\n string for cache busting purposes. If version is set to false, a\n version number is automatically added equal to current installed\n WordPress version. If set to null, no version is added. Default value:\n false</p>\n</blockquote>\n\n<p>But it is very cryptic as to how it actually works. I could not get a version number in <code>wp_enqueue_style</code> to trigger a query param like <code>?ver=1.2.3</code> on my stylesheet. However setting it to true allows the stylesheet's declared version to <code>cache bust</code> the stylesheet. (read on)</p>\n\n<p>Within your style.css you must name your theme. This is required by WP. However other options such as <code>version</code> is what wp_enqueue_style's version boolean gives reference too.</p>\n\n<pre><code>/******************************************************************\nSite Name: MySite.com\nAuthor: @BenRacicot\nVersion: 4.0 // <- wp_enqueue_style's version number\nStylesheet: Main Stylesheet\n******************************************************************/\n</code></pre>\n\n<p>Now when I change that to <code>Version: 4.1</code> I get <code>style.css?cache-bust=0.24135995238933283</code></p>\n"
},
{
"answer_id": 293495,
"author": "Mr. HK",
"author_id": 110110,
"author_profile": "https://wordpress.stackexchange.com/users/110110",
"pm_score": 2,
"selected": false,
"text": "<p>You may simply use <code>time()</code> at a time of enqueue style or script like this..</p>\n\n<p>Without using wordpress <code>wp_enqueue_style()</code> function </p>\n\n<pre><code><link rel='stylesheet' id='xxxx' href='https://www. site css/ styles.css?ver=<?php echo time(); ?>' type='text/css' media='all' />\n</code></pre>\n\n<p>Using <code>wp_enqueue_style()</code> function</p>\n\n<pre><code>wp_enqueue_style('style_sheet_name', get_stylesheet_directory_uri() . '/custom_style.css', '', time());\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<pre><code>wp_enqueue_style('style_sheet_name', get_stylesheet_uri() . '/custom_style.css', '', time());\n</code></pre>\n"
}
] |
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></a> \"Retrieves the translated string from the translate() function\" without echoing. <code>_e()</code> does the same thing but echos the output.</p>\n\n<p>For more information, take a look at these help articles:</p>\n\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/\" rel=\"nofollow noreferrer\">Internationalization</a></p></li>\n<li><p><a href=\"https://developer.wordpress.org/plugins/internationalization/localization/\" rel=\"nofollow noreferrer\">Localization</a></p></li>\n<li><p><a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/\" rel=\"nofollow noreferrer\"><strong>How to Internationalize Your Plugin</strong></a></p></li>\n<li><p><a href=\"https://developer.wordpress.org/plugins/internationalization/security/\" rel=\"nofollow noreferrer\">Internationalization Security</a></p></li>\n</ul>\n"
},
{
"answer_id": 247727,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>It is probably good to know. The foundation of the internalization is the <code>translate</code> function </p>\n\n<pre><code>File: wp-includes/l10n.php\n78: /**\n79: * Retrieve the translation of $text.\n80: *\n81: * If there is no translation, or the text domain isn't loaded, the original text is returned.\n82: *\n83: * *Note:* Don't use translate() directly, use __() or related functions.\n84: *\n85: * @since 2.2.0\n86: *\n87: * @param string $text Text to translate.\n88: * @param string $domain Optional. Text domain. Unique identifier for retrieving translated strings.\n89: * Default 'default'.\n90: * @return string Translated text\n91: */\n92: function translate( $text, $domain = 'default' ) {\n</code></pre>\n\n<p>Anytime you call any of the wrappers</p>\n\n<pre><code>File:wp-includes/l10n.php\n172: function __( $text, $domain = 'default' ) {\n173: return translate( $text, $domain );\n174: }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>File: wp-includes/l10n.php\n188: function esc_attr__( $text, $domain = 'default' ) {\n189: return esc_attr( translate( $text, $domain ) );\n190: }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>File: wp-includes/l10n.php\n217: function _e( $text, $domain = 'default' ) {\n218: echo translate( $text, $domain );\n219: }\n</code></pre>\n\n<p>or many other from <code>wp-includes/l10n.php</code>, this function will be called. But you never call this function directly.</p>\n"
}
] |
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<pre><code>add_filter( 'wp_authenticate_user', 'my_theme_authenticate_user', 1 );\n\nfunction my_theme_authenticate_user( $user ) {\n\n if ( is_wp_error( $user ) ) {\n return $user;\n }\n\n\n $on_hold = get_user_meta($user->ID, 'holdUser', true );\n if ( (int)$on_hold == 1) {\n return new WP_Error( 'get lost' );\n }\n\n return $user;\n}\n</code></pre>\n\n<p>(put the above in your theme's functions.php)</p>\n\n<p>Also, I think you may need to give your form element <code>name=\"loginform\"</code>, in order for WordPress to pick up on it and treat it just like the native WP login form and fire all the same hooks, but not sure on this.</p>\n\n<p>PS: It's recommended to use <code>wp_login_form()</code> to create your custom login form, as you'll get other features such as easy way of specifying a redirect URL. <a href=\"https://codex.wordpress.org/Function_Reference/wp_login_form\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_login_form</a></p>\n"
},
{
"answer_id": 247743,
"author": "P1nGu1n",
"author_id": 107933,
"author_profile": "https://wordpress.stackexchange.com/users/107933",
"pm_score": 3,
"selected": true,
"text": "<pre><code>function myplugin_authenticate_on_hold($user)\n{\n // username and password are correct\n if ($user instanceof WP_User) {\n $on_hold = get_user_meta($user->ID, 'is_on_hold', true);\n if ($on_hold) {\n return new WP_Error('on_hold_error', 'You are on hold');\n }\n }\n\n return $user;\n}\n\nadd_filter('authenticate', 'myplugin_authenticate_on_hold', 21);\n</code></pre>\n\n<p>The priority needs to be 21, as <code>wp_authenticate_username_password</code> and <code>wp_authenticate_email_password</code> are priority 20. They return an object of the type <code>WP_User</code> 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.</p>\n\n<p>Edit: why aren't you using the default login form?</p>\n"
}
] |
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/get-the-current-page-url-including-pagination\">here</a> (not accepted), this snippet should do the trick: <code>home_url(add_query_arg(NULL, NULL));</code>. </p>\n"
},
{
"answer_id": 247733,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 5,
"selected": true,
"text": "<p>You can get the current URL through <code>home_url( $wp->request )</code>.</p>\n\n<p>Try the example below:</p>\n\n<pre><code>global $wp;\n\n// get current url with query string.\n$current_url = home_url( $wp->request ); \n\n// get the position where '/page.. ' text start.\n$pos = strpos($current_url , '/page');\n\n// remove string from the specific postion\n$finalurl = substr($current_url,0,$pos);\n\n\necho $finalurl;\n</code></pre>\n"
},
{
"answer_id": 247739,
"author": "Ihor Vorotnov",
"author_id": 47359,
"author_profile": "https://wordpress.stackexchange.com/users/47359",
"pm_score": 3,
"selected": false,
"text": "<p>Answer by <a href=\"https://wordpress.stackexchange.com/a/247733/47359\">Govind Kumar</a> worked, however, it only returned the URL if /page/{pagenum}/ was present in the URL and returned nothing if not. I needed a universal solution that will always return the base URL without pagination, so I modified Govind's code a bit and wrapped into a function:</p>\n\n<pre><code>function get_nopaging_url() {\n\n global $wp;\n\n $current_url = home_url( $wp->request );\n $position = strpos( $current_url , '/page' );\n $nopaging_url = ( $position ) ? substr( $current_url, 0, $position ) : $current_url;\n\n return trailingslashit( $nopaging_url );\n\n}\n\necho get_nopaging_url();\n</code></pre>\n\n<p>Now, it always returns correct URL. </p>\n\n<p>(<em>This is useful if you need to implement some kind of post filters that add a param to filter posts by, let's say, a meta filed. So, even if a user sets the filter param on page X, the new filtered results will always start from the base URL, not page X and throwing 404 if there's less filtered posts.</em>)</p>\n"
},
{
"answer_id": 264266,
"author": "Lorenzo",
"author_id": 33443,
"author_profile": "https://wordpress.stackexchange.com/users/33443",
"pm_score": 2,
"selected": false,
"text": "<p>My specifics were very similar to Ihor Vorotnov's, exept that I had more than one parameter. So, starting from his answer, I modified the code to use a regular expression:</p>\n\n<pre><code>function get_nopaging_url() {\n $current_url = $_SERVER[REQUEST_URI];\n\n $pattern = '/page\\\\/[0-9]+\\\\//i';\n $nopaging_url = preg_replace($pattern, '', $current_url);\n\n return $nopaging_url;\n}\n</code></pre>\n"
},
{
"answer_id": 306523,
"author": "Chief Alchemist",
"author_id": 18343,
"author_profile": "https://wordpress.stackexchange.com/users/18343",
"pm_score": -1,
"selected": false,
"text": "<pre><code>trait TraitURLStrip {\n\n /**\n * Strips off paging and query string. Returns a filter-the-results friendly URL\n *\n * @param bool $str_url\n * @param string $str_page\n *\n * @return bool|string\n */\n protected function urlStrip( $str_url = false , $str_page = 'page' ){\n\n if ( is_string( $str_url) ) {\n\n $arr_parse_url = wp_parse_url( $str_url );\n\n $str_path_no_page = '';\n if ( isset( $arr_parse_url['path'] ) ) {\n\n // if we're paging then remove that. please!\n $str_path_no_page = preg_replace( \"/\\/{$str_page}\\/[0-9]*\\/$/\", \"/\", $arr_parse_url['path'] );\n\n }\n\n $str_scheme_host = \"{$arr_parse_url['scheme']}://{$arr_parse_url['host']}\";\n\n return $str_scheme_host . $str_path_no_page;\n }\n return false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 337383,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 4,
"selected": false,
"text": "<p>Actually the easiest would be to use <a href=\"https://developer.wordpress.org/reference/functions/get_pagenum_link/\" rel=\"noreferrer\"><code>get_pagenum_link()</code></a> which will return you the current URL without any <code>/page/*</code> paramaters.</p>\n\n<hr>\n\n<h3>Bonus</h3>\n\n<p>You can also simply use it to build \"Previous\" and \"Next\" links dynamically using the <code>'paged'</code> query variable:</p>\n\n<pre><code>// Get the current page number.\n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n\n$first_page = '<a href=\"' . get_pagenum_link() . '\" class=\"page-first\"><<</a>';\n$prev_page = '<a href=\"' . get_pagenum_link($paged - 1) . '\" class=\"page-prev\"><</a>';\n$next_page = '<a href=\"' . get_pagenum_link($paged + 1) . ' class=\"page-next\">></a>';\n\n// And having a `WP_Query` object you can also build the link for the last page:\n$max = $the_query->max_num_pages;\n$last_page = '<a href=\"' . get_pagenum_link($max) . '\" class=\"page-last\">>></a>';\n</code></pre>\n"
},
{
"answer_id": 344678,
"author": "Larzan",
"author_id": 34517,
"author_profile": "https://wordpress.stackexchange.com/users/34517",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to <strong>remove all possible pagination combinations</strong> then use this snippet:</p>\n\n<pre><code>// remove pagination from url\n$pattern = '/page(\\/)*([0-9\\/])*/i';\n$url = preg_replace($pattern, '', $GLOBALS['wp']->request);\n</code></pre>\n\n<p>It will take care of</p>\n\n<pre><code>/page\n/page/\n/page/1\n/page/1/\n...\n</code></pre>\n\n<p>and is case insensitive, works for any pagination page number and also will remove any combination of trailing number/number/number...\n(tests here: <a href=\"https://regex101.com/r/9fQaLC/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/9fQaLC/1</a>)</p>\n\n<p>If you want to get the full url with leading http(s) just add</p>\n\n<pre><code>$url = home_url($url);\n</code></pre>\n\n<p>In that line you can also add any custom GET parameter like so</p>\n\n<pre><code>$url = home_url($url . '?typ=test');\n</code></pre>\n"
},
{
"answer_id": 403782,
"author": "Андрей Рабой",
"author_id": 198220,
"author_profile": "https://wordpress.stackexchange.com/users/198220",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function getCurrentUrlSeo() {\n global $wp;\n $current_url = home_url($wp->request);\n $pos = mb_strpos($current_url, '/page');\n $finalurl = $pos ? substr($current_url, 0, $pos) : $current_url;\n return $finalurl.'/';\n}\n</code></pre>\n"
}
] |
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 want to give terms a 'menu_order' you will need to create this yourself.</p>\n\n<p>As long as your WP is >= 4.4.0, you can make use of the feature <code>term_meta</code>.</p>\n\n<p>This is to terms what post meta is to posts.</p>\n\n<p>You can create a 'menu_order' 'custom field' for terms and then you can set the menu order when creating/editing a term. </p>\n\n<p>The relevant functions are:</p>\n\n<pre><code>add_term_meta();\n\nupdate_term_meta();\n\nget_term_meta();\n\ndelete_term_meta();\n</code></pre>\n\n<p>See here - <a href=\"https://codex.wordpress.org/Function_Reference/add_term_meta\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_term_meta</a></p>\n\n<p>And when query, your code won't do the trick for term meta. You need to write your own widget, that contains <code>get_terms()</code>. E.g.</p>\n\n<pre><code>$args = array(\n 'taxonomy' => 'taxonomy_name', //can be array with multiple tax\n 'meta_key' => 'menu_order',\n 'orderby' => 'meta_value',\n 'order' => 'DESC',\n);\n\n$terms = get_terms($args);\n</code></pre>\n\n<p>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.</p>\n\n<p>If you Google 'wp term meta' you'll find out how to do it.</p>\n\n<p>You will need 4 or 5 functions in all.</p>\n\n<p>The hooks you will use are:</p>\n\n<pre><code>{$taxonomy}_add_form_fields // add the custom field to the 'new term' form\n\n{$taxonomy}_edit_form_fields // add the custom field to the 'edit term' form\n\ncreate_{$taxonomy} // for saving the term meta from the 'new term' form\n\nedit_{$taxonomy} // for saving the term meta from the 'edit term' form\n\nmanage_edit-{$taxonomy}_columns // OPTIONAL adds a column, for the custom field, in the terms table for the taxonomy\n</code></pre>\n\n<p>Or, use a plugin like <a href=\"https://wordpress.org/plugins/wp-custom-taxonomy-meta/\" rel=\"nofollow noreferrer\">this one</a> (or copy the code in it).</p>\n"
},
{
"answer_id": 247753,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<p>If you mean <code>term_order</code>, then you could use the <code>tag_cloud_sort</code> filter to handle the sorting via PHP.</p>\n\n<p>Here's an example, using <code>usort</code>:</p>\n\n<pre><code>add_filter( 'tag_cloud_sort', function( $tags, $args )\n{\n // Nothing to do if no tags\n if( empty( $tags ) || ! is_array( $tags ) )\n return $tags;\n\n // Custom tag sort\n uasort( $tags, function( $a, $b )\n {\n if( $a->term_order === $b->term_order )\n return 0;\n\n return $a->term_order < $b->term_order ? - 1 : 1; // ASC\n } );\n\n return $tags;\n}, 10, 2 );\n</code></pre>\n\n<p>that can be simplified in PHP 7 by using the <a href=\"https://wiki.php.net/rfc/combined-comparison-operator\" rel=\"nofollow noreferrer\">spaceship</a> comparison operator:</p>\n\n<pre><code>add_filter( 'tag_cloud_sort', function( $tags, $args )\n{\n // Nothing to do if no tags\n if( empty( $tags ) || ! is_array( $tags ) )\n return $tags;\n\n // Custom tag sort\n usort( $tags, function( $a, $b )\n {\n return $a->term_order <=> $b->term_order; // ASC (swap $a and $b for DESC)\n } );\n\n return $tags;\n}, 10, 2 );\n</code></pre>\n\n<p>The <code>wp_generate_tag_cloud()</code> function uses <a href=\"http://php.net/manual/en/function.uasort.php\" rel=\"nofollow noreferrer\"><code>uasort()</code></a>, but I don't think we need to preserve the index association here.</p>\n\n<p>PS: </p>\n\n<p>The <code>wp_cloud_tag()</code> function uses <code>get_terms()</code>, so an alternative could be to support <code>term_order</code> ordering in <code>get_terms()</code> via the <code>get_terms_orderby</code> filter. See e.g. a recent <a href=\"https://wordpress.stackexchange.com/a/243134/26350\">answer</a> here. I just tested the <code>term_order</code> ordering by using the plugin mentioned by OP in the question that was answered there.</p>\n"
}
] |
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 want to give terms a 'menu_order' you will need to create this yourself.</p>\n\n<p>As long as your WP is >= 4.4.0, you can make use of the feature <code>term_meta</code>.</p>\n\n<p>This is to terms what post meta is to posts.</p>\n\n<p>You can create a 'menu_order' 'custom field' for terms and then you can set the menu order when creating/editing a term. </p>\n\n<p>The relevant functions are:</p>\n\n<pre><code>add_term_meta();\n\nupdate_term_meta();\n\nget_term_meta();\n\ndelete_term_meta();\n</code></pre>\n\n<p>See here - <a href=\"https://codex.wordpress.org/Function_Reference/add_term_meta\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_term_meta</a></p>\n\n<p>And when query, your code won't do the trick for term meta. You need to write your own widget, that contains <code>get_terms()</code>. E.g.</p>\n\n<pre><code>$args = array(\n 'taxonomy' => 'taxonomy_name', //can be array with multiple tax\n 'meta_key' => 'menu_order',\n 'orderby' => 'meta_value',\n 'order' => 'DESC',\n);\n\n$terms = get_terms($args);\n</code></pre>\n\n<p>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.</p>\n\n<p>If you Google 'wp term meta' you'll find out how to do it.</p>\n\n<p>You will need 4 or 5 functions in all.</p>\n\n<p>The hooks you will use are:</p>\n\n<pre><code>{$taxonomy}_add_form_fields // add the custom field to the 'new term' form\n\n{$taxonomy}_edit_form_fields // add the custom field to the 'edit term' form\n\ncreate_{$taxonomy} // for saving the term meta from the 'new term' form\n\nedit_{$taxonomy} // for saving the term meta from the 'edit term' form\n\nmanage_edit-{$taxonomy}_columns // OPTIONAL adds a column, for the custom field, in the terms table for the taxonomy\n</code></pre>\n\n<p>Or, use a plugin like <a href=\"https://wordpress.org/plugins/wp-custom-taxonomy-meta/\" rel=\"nofollow noreferrer\">this one</a> (or copy the code in it).</p>\n"
},
{
"answer_id": 247753,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<p>If you mean <code>term_order</code>, then you could use the <code>tag_cloud_sort</code> filter to handle the sorting via PHP.</p>\n\n<p>Here's an example, using <code>usort</code>:</p>\n\n<pre><code>add_filter( 'tag_cloud_sort', function( $tags, $args )\n{\n // Nothing to do if no tags\n if( empty( $tags ) || ! is_array( $tags ) )\n return $tags;\n\n // Custom tag sort\n uasort( $tags, function( $a, $b )\n {\n if( $a->term_order === $b->term_order )\n return 0;\n\n return $a->term_order < $b->term_order ? - 1 : 1; // ASC\n } );\n\n return $tags;\n}, 10, 2 );\n</code></pre>\n\n<p>that can be simplified in PHP 7 by using the <a href=\"https://wiki.php.net/rfc/combined-comparison-operator\" rel=\"nofollow noreferrer\">spaceship</a> comparison operator:</p>\n\n<pre><code>add_filter( 'tag_cloud_sort', function( $tags, $args )\n{\n // Nothing to do if no tags\n if( empty( $tags ) || ! is_array( $tags ) )\n return $tags;\n\n // Custom tag sort\n usort( $tags, function( $a, $b )\n {\n return $a->term_order <=> $b->term_order; // ASC (swap $a and $b for DESC)\n } );\n\n return $tags;\n}, 10, 2 );\n</code></pre>\n\n<p>The <code>wp_generate_tag_cloud()</code> function uses <a href=\"http://php.net/manual/en/function.uasort.php\" rel=\"nofollow noreferrer\"><code>uasort()</code></a>, but I don't think we need to preserve the index association here.</p>\n\n<p>PS: </p>\n\n<p>The <code>wp_cloud_tag()</code> function uses <code>get_terms()</code>, so an alternative could be to support <code>term_order</code> ordering in <code>get_terms()</code> via the <code>get_terms_orderby</code> filter. See e.g. a recent <a href=\"https://wordpress.stackexchange.com/a/243134/26350\">answer</a> here. I just tested the <code>term_order</code> ordering by using the plugin mentioned by OP in the question that was answered there.</p>\n"
}
] |
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=\"nofollow noreferrer\">documentation</a> <code>register_nav_menu</code> 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 <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\">wp_nav_menu</a>. Like the following:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// header.php (or similar)\nwp_nav_menu([\n 'menu' => (is_page('about-us') ? 'primary-navigation' ? 'example-menu'),\n]);\n</code></pre>\n<p>Otherwise you could also register a menu and change the value of the <code>theme_location</code> parameter to make the menu configurable by the user.</p>\n<h3>Update:</h3>\n<p>To achieve this via a filter hook</p>\n<pre class=\"lang-php prettyprint-override\"><code>// functions.php\nadd_filter('wp_nav_menu_args', function ($args) {\n if (is_page('about-us')) {\n $args['menu'] = 'my-custom-menu';\n }\n return $args;\n});\n</code></pre>\n"
},
{
"answer_id": 247777,
"author": "Dan.",
"author_id": 97196,
"author_profile": "https://wordpress.stackexchange.com/users/97196",
"pm_score": 0,
"selected": false,
"text": "<p>1 - Copy the parent theme's <code>header.php</code> into your child theme.</p>\n\n<p>2 - To create custom fields, if you are not too knowledgable of WP, I suggest using the <a href=\"http://www.advancedcustomfields.com\" rel=\"nofollow noreferrer\">Advanced Custom Fields plugin</a>.</p>\n\n<p>Read the docs on their website. You want to create a select/dropdown or radio type field and have it for all post types and pages.</p>\n\n<p>For each menu that you have, give the custom field a value.</p>\n\n<p>Give the custom field a default value - the one for the menu that you will be using most (so that it'll save you some time)</p>\n\n<p>3 - Give the other pages/posts the other menu.</p>\n\n<p>4 - In your child theme's header.php, change this:</p>\n\n<pre><code><?php if('true' == $ubermenu):\n wp_nav_menu(array(\n 'theme_location' => 'Primary Navigation' ,\n 'depth' => 0 ,\n 'container' => false ,\n 'walker' => new description_walker() ));\nelse: ?>\n <ul id=\"menu-main-nav\" class=\"sf-menu\">\n <?php wp_nav_menu(array(\n 'theme_location' => 'Primary Navigation' ,\n 'depth' => 0 ,\n 'container' => false ,\n 'walker' => new description_walker() )); ?>\n</ul>\n<?php endif; //end uberMenu check ?>\n</code></pre>\n\n<p>To:</p>\n\n<pre><code><?php \n$menu_to_use = get_field(get_the_ID(), 'meta_key_of_custom_field');\nif('true' == $ubermenu):\n wp_nav_menu(array(\n 'theme_location' => $menu_to_use, // make sure that the values of the custom field are the names of the menus (e.g. Primary Menu)\n 'depth' => 0 ,\n 'container' => false ,\n 'walker' => new description_walker() ));\nelse: ?>\n <ul id=\"menu-main-nav\" class=\"sf-menu\">\n <?php wp_nav_menu(array(\n 'theme_location' => $menu_to_use, // make sure that the values of the custom field are the names of the menus (e.g. Primary Menu)\n 'depth' => 0 ,\n 'container' => false ,\n 'walker' => new description_walker() )); ?>\n</ul>\n<?php endif; //end uberMenu check ?>\n</code></pre>\n"
}
] |
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 href=\"http://php.net/manual/en/function.strpos.php\" rel=\"noreferrer\"><code>strpos()</code></a></p>\n\n<pre><code>global $post;\n\nif( false !== strpos( $post->post_name, 'beef' ) ) {\n // Do Things\n}\n</code></pre>\n\n<p>The above returns true if <code>beef</code> is found somewhere in the post slug.</p>\n"
},
{
"answer_id": 247793,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>In a similar way as @Howdy_McGee, we might try to construct an helper function:</p>\n\n<pre><code>/**\n * @param $s String \n * @return bool\n */\nfunction queried_post_name_contains_wpse247782( $s )\n{\n $obj = get_queried_object();\n\n return $obj instanceof \\WP_Post // Make sure it's a post object\n && false !== strpos( $obj->post_name, $s ); // post name contains it\n}\n</code></pre>\n\n<p>and use it like:</p>\n\n<pre><code>if( is_single() && queried_post_name_contains_wpse247782( 'beef' ) )\n{\n // ...\n}\n</code></pre>\n\n<p>Hope you can extend it futher to your needs!</p>\n"
}
] |
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=\"noreferrer\">here</a>, you could add this to your functions.php</p>\n\n<pre><code>// retrieves the attachment ID from the file URL\nfunction pippin_get_image_id($image_url) {\n global $wpdb;\n $attachment = $wpdb->get_col($wpdb->prepare(\"SELECT ID FROM $wpdb->posts WHERE guid='%s';\", $image_url )); \n return $attachment[0]; \n}\n</code></pre>\n\n<p>But to use it, you need the full image URL.</p>\n\n<pre><code>$img_url = get_bloginfo('url') . '/bc/wp-content/uploads/placeholder-image.png';\n\nif ( $img_id = pippin_get_image_id($img_url) ) {\n // Using wp_get_attachment_image should return your alt text added in the WordPress admin.\n echo wp_get_attachment_image( $img_id, 'full' );\n} else {\n // Fallback in case it's not found.\n echo '<img src=\"' . $img_url . '\" alt=\"\" />';\n}\n</code></pre>\n"
},
{
"answer_id": 247797,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": false,
"text": "<p>This is a slightly modified version of the <a href=\"https://pippinsplugins.com/retrieve-attachment-id-from-image-url/\" rel=\"nofollow noreferrer\">Pippin Function</a>. Since it returns a post ID we can use it to get the alternative text which is saved as Post Meta:</p>\n\n<pre><code>/**\n * Get image alt text by image URL\n *\n * @param String $image_url\n *\n * @return Bool | String\n */\nfunction image_alt_by_url( $image_url ) {\n global $wpdb;\n\n if( empty( $image_url ) ) {\n return false;\n }\n\n $query_arr = $wpdb->get_col( $wpdb->prepare( \"SELECT ID FROM {$wpdb->posts} WHERE guid='%s';\", strtolower( $image_url ) ) );\n $image_id = ( ! empty( $query_arr ) ) ? $query_arr[0] : 0;\n\n return get_post_meta( $image_id, '_wp_attachment_image_alt', true );\n}\n</code></pre>\n"
}
] |
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 * Add a message to the password form.\n *\n * @wp-hook the_password_form\n * @param string $form\n * @return string\n */\nfunction wpse_71284_custom_post_password_msg( $form )\n{\n // No cookie, the user has not sent anything until now.\n if ( ! isset ( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) )\n return $form;\n\n // No cookie, person just submitted the form on this page and got the password wrong\n if (wp_get_referer() == get_permalink()) {\n // Translate and escape.\n $msg = esc_html__( 'Sorry, your password is wrong.', 'your_text_domain' );\n\n // We have a cookie, but it doesn’t match the password.\n $msg = \"<p class='custom-password-message'>$msg</p>\";\n } else {\n $msg = \"\";\n }\n return $msg . $form;\n}\n</code></pre>\n"
},
{
"answer_id": 393636,
"author": "Antonio Blanco Oliva",
"author_id": 170918,
"author_profile": "https://wordpress.stackexchange.com/users/170918",
"pm_score": 0,
"selected": false,
"text": "<p>for me, this code works:</p>\n<pre><code>function my_password_form() {\n global $post;\n\n $label = 'pwbox-'.( empty( $post->ID ) ? rand() : $post->ID );\n\n $passwordProtectedPageURL = get_the_permalink();\n $wrongPassword = ' ';\n\n if( ( sanitize_text_field( $_SERVER["HTTP_REFERER"] ) === $passwordProtectedPageURL ) && isset ( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] )){\n $wrongPassword = '<span style="color:#ed1b24;font-weight:bold;">Contraseña incorrecta, por favor inténtalo de nuevo.</span>';\n setcookie ('wp-postpass_' . COOKIEHASH, null, -1);\n\n }\n\n\n $form = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" method="post" class="post-password-form">\n' . "<p>Este contenido está protegido por contraseña. Para verlo, por favor, introduce tu contraseña a continuación:</p>" . '\n<p><label for="' . $label . '">' . __( "Password:" ) . ' <input name="post_password" id="' . $label . '" type="password" size="20" maxlength="20" /></label>\n<input type="submit" name="Submit" value="' . esc_attr__( "Submit" ) . '" /></p>\n</form><p>' . $wrongPassword . '</p>';\n\n return $form;\n}\nadd_filter( 'the_password_form', 'my_password_form' );\n</code></pre>\n<p>The messages are in spanish, but they are easy to change.</p>\n"
}
] |
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:</p>\n\n<pre><code>if( is_front_page() ){\n echo 'Front page!';\n}\n</code></pre>\n\n<p>You must have it configured in the settings to use:</p>\n\n<p><code>A static page (select below)</code> instead of <code>Your latest posts</code></p>\n\n<p>If you want <code>is_front_page()</code> to only return TRUE when viewing the page you select from the dropdown for <strong>Front Page</strong> (which it sounds like you do)</p>\n\n<p>You can then use <code>is_home()</code> 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”.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/is_home/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/is_home/</a></p>\n\n<p>Whether <a href=\"https://developer.wordpress.org/reference/functions/is_home/\" rel=\"noreferrer\">is_home()</a> or <a href=\"https://developer.wordpress.org/reference/functions/is_front_page/\" rel=\"noreferrer\">is_front_page()</a> return <code>true</code> or <code>false</code> depends on the values of certain option values:</p>\n\n<ul>\n <li><code>get_option( 'show_on_front' )</code>: returns either <code>'posts'</code> or <code>'page'</code></li>\n <li><code>get_option( 'page_on_front' )</code>: returns the <code>ID</code> of the static page assigned to the front page</li>\n <li><code>get_option( 'page_for_posts' )</code>: returns the <code>ID</code> of the static page assigned to the blog posts index (posts page)</li>\n</ul>\n\n<p>When using these query conditionals:</p>\n\n<ul>\n <li>If <code>'posts' == get_option( 'show_on_front' )</code>:\n<ul>\n <li>On the site front page:\n<ul>\n <li><code>is_front_page()</code> will return <code>true</code></li>\n <li><code>is_home()</code> will return <code>true</code></li>\n</ul>\n</li>\n <li>If assigned, WordPress ignores the pages assigned to display the site front page or the blog posts index</li>\n</ul>\n</li>\n <li>If <code>'page' == get_option( 'show_on_front' )</code>:\n<ul>\n <li>On the page assigned to display the site front page:\n<ul>\n <li><code>is_front_page()</code> will return <code>true</code></li>\n <li><code>is_home()</code> will return <code>false</code></li>\n</ul>\n</li>\n <li>On the page assigned to display the blog posts index:\n<ul>\n <li><code>is_front_page()</code> will return <code>false</code></li>\n <li><code>is_home()</code> will return <code>true</code></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n"
},
{
"answer_id": 339693,
"author": "Brian Layman",
"author_id": 2785,
"author_profile": "https://wordpress.stackexchange.com/users/2785",
"pm_score": 0,
"selected": false,
"text": "<p>Just for the record, your original statement would have worked if you had called a function by including parens instead of using what looked like a non-existent constant to the PHP interpreter. The constant <em>is_front_page</em> was evaluated as the string \"is_front_page\" and since \"is_front_page\" is not == false, it evaluated as true and \"frontPageLogo\" was always echoed. Get it?</p>\n\n<p>So instead of:</p>\n\n<pre><code><?php echo ( is_front_page ) ? 'frontPageLogo' : NULL; ?>\n</code></pre>\n\n<p>You wanted:</p>\n\n<pre><code> <?php echo ( is_front_page() ) ? 'frontPageLogo' : NULL; ?>\n</code></pre>\n"
}
] |
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:</p>\n\n<pre><code>if( is_front_page() ){\n echo 'Front page!';\n}\n</code></pre>\n\n<p>You must have it configured in the settings to use:</p>\n\n<p><code>A static page (select below)</code> instead of <code>Your latest posts</code></p>\n\n<p>If you want <code>is_front_page()</code> to only return TRUE when viewing the page you select from the dropdown for <strong>Front Page</strong> (which it sounds like you do)</p>\n\n<p>You can then use <code>is_home()</code> 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”.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/is_home/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/is_home/</a></p>\n\n<p>Whether <a href=\"https://developer.wordpress.org/reference/functions/is_home/\" rel=\"noreferrer\">is_home()</a> or <a href=\"https://developer.wordpress.org/reference/functions/is_front_page/\" rel=\"noreferrer\">is_front_page()</a> return <code>true</code> or <code>false</code> depends on the values of certain option values:</p>\n\n<ul>\n <li><code>get_option( 'show_on_front' )</code>: returns either <code>'posts'</code> or <code>'page'</code></li>\n <li><code>get_option( 'page_on_front' )</code>: returns the <code>ID</code> of the static page assigned to the front page</li>\n <li><code>get_option( 'page_for_posts' )</code>: returns the <code>ID</code> of the static page assigned to the blog posts index (posts page)</li>\n</ul>\n\n<p>When using these query conditionals:</p>\n\n<ul>\n <li>If <code>'posts' == get_option( 'show_on_front' )</code>:\n<ul>\n <li>On the site front page:\n<ul>\n <li><code>is_front_page()</code> will return <code>true</code></li>\n <li><code>is_home()</code> will return <code>true</code></li>\n</ul>\n</li>\n <li>If assigned, WordPress ignores the pages assigned to display the site front page or the blog posts index</li>\n</ul>\n</li>\n <li>If <code>'page' == get_option( 'show_on_front' )</code>:\n<ul>\n <li>On the page assigned to display the site front page:\n<ul>\n <li><code>is_front_page()</code> will return <code>true</code></li>\n <li><code>is_home()</code> will return <code>false</code></li>\n</ul>\n</li>\n <li>On the page assigned to display the blog posts index:\n<ul>\n <li><code>is_front_page()</code> will return <code>false</code></li>\n <li><code>is_home()</code> will return <code>true</code></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n"
},
{
"answer_id": 339693,
"author": "Brian Layman",
"author_id": 2785,
"author_profile": "https://wordpress.stackexchange.com/users/2785",
"pm_score": 0,
"selected": false,
"text": "<p>Just for the record, your original statement would have worked if you had called a function by including parens instead of using what looked like a non-existent constant to the PHP interpreter. The constant <em>is_front_page</em> was evaluated as the string \"is_front_page\" and since \"is_front_page\" is not == false, it evaluated as true and \"frontPageLogo\" was always echoed. Get it?</p>\n\n<p>So instead of:</p>\n\n<pre><code><?php echo ( is_front_page ) ? 'frontPageLogo' : NULL; ?>\n</code></pre>\n\n<p>You wanted:</p>\n\n<pre><code> <?php echo ( is_front_page() ) ? 'frontPageLogo' : NULL; ?>\n</code></pre>\n"
}
] |
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_list_pages()</code> function. </p>\n\n<p>The purpose of Walker class is </p>\n\n<blockquote>\n <p>It simply traces each branch of your tree: it has to be extended by\n other classes which tell it what to do for each element it comes\n across.</p>\n</blockquote>\n\n<p>Put this class inside your <code>functions.php</code> file or <code>plugins</code> file.</p>\n\n<pre><code>class linkModifyWalker extends Walker_Page {\n\n\nfunction start_lvl( &$output, $depth = 0, $args = array() ) {\n $indent = str_repeat(\"\\t\", $depth);\n $output .= \"\\n$indent<ul class='dropdown-menu children'>\\n\";\n}\n\n\nfunction start_el( &$output, $page, $depth = 0, $args = array(), $current_page = 0 ) {\n if ( $depth )\n $indent = str_repeat(\"\\t\", $depth);\n else\n $indent = '';\n\n extract($args, EXTR_SKIP);\n $css_class = array('page_item', 'page-item-'.$page->ID);\n\n if( isset( $args['pages_with_children'][ $page->ID ] ) )\n $css_class[] = 'page_item_has_children dropdown';\n\n if ( !empty($current_page) ) {\n $_current_page = get_post( $current_page );\n if ( in_array( $page->ID, $_current_page->ancestors ) )\n $css_class[] = 'current_page_ancestor';\n if ( $page->ID == $current_page )\n $css_class[] = 'current_page_item';\n elseif ( $_current_page && $page->ID == $_current_page->post_parent )\n $css_class[] = 'current_page_parent';\n } elseif ( $page->ID == get_option('page_for_posts') ) {\n $css_class[] = 'current_page_parent';\n }\n\n\n $css_class = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) );\n $output .= $indent . '<li class=\"' . $css_class . '\"><a href=\"#' .$page->ID . '\">' . $link_before . apply_filters( 'the_title', $page->post_title, $page->ID ) . $link_after . '</a>';\n\n\n }\n}\n</code></pre>\n\n<p>We have just created <code>linkModifyWalker</code> class now,We need to pass it's object to the <code>wp_list_pages()</code> as a argument. \n<code>'walker' => new linkModifyWalker()</code></p>\n\n<pre><code><ul id=\"markdown-toc\">\n <li><h3><a href=\"#contents\">Contents</a></h3></li>\n <ul id=\"my_cutom_type-list\">\n <?php \n wp_list_pages( array(\n 'post_type'=> 'manual',\n 'walker' => new linkModifyWalker()\n ) ); \n ?>\n </ul>\n </ul>\n</code></pre>\n\n<p>To know more about what is Walker Class. I recommend you to visit below link.</p>\n\n<p><a href=\"https://code.tutsplus.com/tutorials/understanding-the-walker-class--wp-25401\" rel=\"nofollow noreferrer\">Understanding the Walker Class</a></p>\n"
},
{
"answer_id": 247867,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>You could add a filter on <code>post_type_link</code>, which allows modification of custom post type permalinks before they are output.</p>\n\n<p>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:</p>\n\n<pre><code>function wpd_list_pages_permalink_filter( $permalink, $page ){\n return '#' . $page->ID;\n}\n</code></pre>\n\n<p>Then you can add and remove the filter when using <code>wp_list_pages</code>:</p>\n\n<pre><code>add_filter( 'post_type_link', 'wpd_list_pages_permalink_filter', 10, 2 );\n\nwp_list_pages();\n\nremove_filter( 'post_type_link', 'wpd_list_pages_permalink_filter', 10, 2 );\n</code></pre>\n\n<p>If your menu contained the built in <code>page</code> post type, you would use the <code>page_link</code> filter. Note in that case the 2nd argument is only the page's ID, not the full page object like in the <code>post_type_link</code> filter.</p>\n"
}
] |
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 you have to access category id by passing array key, like this <code>$postcat[0]->term_id</code></p>\n\n<pre><code>global $post;\n$postcat = get_the_category( $post->ID );\n\n// try print_r($postcat) ; \n\nif ( ! empty( $postcat ) ) {\n echo esc_html( $postcat[0]->name ); \n}\n</code></pre>\n\n<p>Hope this help!</p>\n"
},
{
"answer_id": 307936,
"author": "Nguyễn Tiến Dũng",
"author_id": 146542,
"author_profile": "https://wordpress.stackexchange.com/users/146542",
"pm_score": 0,
"selected": false,
"text": "<pre>\nglobal $post;\n$postcat = get_the_category( $post->ID );\n if ( ! empty( $postcat ) ) {\n foreach ($postcat as $nameCategory) {\n echo $nameCategory->name .' '; \n } \n }?>\n</pre> \n"
},
{
"answer_id": 309790,
"author": "Jan Desta",
"author_id": 45875,
"author_profile": "https://wordpress.stackexchange.com/users/45875",
"pm_score": 1,
"selected": false,
"text": "<p>An improvement to Govind Kumar answer, as the asker askes about <strong>category ID</strong>, not the <em>category name</em>. The property name of the object for category ID is \"<strong>cat_ID</strong>\".</p>\n\n<pre><code>// get cat ID for general view\n$postcat = get_the_category( $query->post->ID );\nif ( ! empty( $postcat ) ) {\n echo $postcat[0]->cat_ID;\n}\n</code></pre>\n"
},
{
"answer_id": 318832,
"author": "swibo",
"author_id": 152766,
"author_profile": "https://wordpress.stackexchange.com/users/152766",
"pm_score": 1,
"selected": true,
"text": "<pre><code>function catName($cat_id) {\n $cat_id = (int) $cat_id;\n $category = &get_category($cat_id);\n return $category->name;\n}\nfunction catLink($cat_id) {\n $category = get_the_category();\n $category_link = get_category_link($cat_id);\n echo $category_link;\n}\n\nfunction catCustom() {\n $cats = get_the_category($post->ID);\n $parent = get_category($cats[1]->category_parent);\n if (is_wp_error($parent)){\n $cat = get_category($cats[0]);\n }\n else{\n $cat = $parent;\n }\n echo '<a href=\"'.get_category_link($cat).'\">'.$cat->name.'</a>'; \n}\n</code></pre>\n\n<p>USE <code><a href=\"<?php catLink(1); ?>\"> <?php catName(1); ?></code></p>\n"
},
{
"answer_id": 374591,
"author": "cameronjonesweb",
"author_id": 65582,
"author_profile": "https://wordpress.stackexchange.com/users/65582",
"pm_score": 3,
"selected": false,
"text": "<p>Old post I know, but <a href=\"https://developer.wordpress.org/reference/functions/wp_get_post_categories/\" rel=\"noreferrer\"><code>wp_get_post_categories</code></a> is likely what you want.</p>\n<pre><code>$cats = wp_get_post_categories( get_the_ID(), array( 'fields' => 'ids' ) );\n</code></pre>\n<p>This will return an array of category IDs like so</p>\n<pre><code>array (size=3)\n 0 => int 13\n 1 => int 15\n 2 => int 120\n</code></pre>\n<p>So if you just want one category ID, you can get that from the first key in the array of category IDs.</p>\n<pre><code>$category_id = $cats[0];\n</code></pre>\n"
}
] |
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 below example will do the example in your question:</p>\n\n<pre><code>add_filter( 'json_url_prefix', 'my_theme_api_slug'); \nfunction my_theme_api_slug( $slug ) { \n return 'mistified';\n}\n</code></pre>\n"
},
{
"answer_id": 253117,
"author": "rorymorris89",
"author_id": 104431,
"author_profile": "https://wordpress.stackexchange.com/users/104431",
"pm_score": 4,
"selected": false,
"text": "<p>Please note that for current versions of WordPress, using the <code>json_url_prefix</code> filter no longer works. </p>\n\n<p>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.</p>\n\n<pre><code>add_filter( 'rest_url_prefix', 'my_theme_api_slug'); \nfunction my_theme_api_slug( $slug ) { return 'api'; }\n</code></pre>\n\n<p>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):</p>\n\n<pre><code>flush_rewrite_rules(true);\n</code></pre>\n"
}
] |
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 to phpmyadmin table wp_posts and replace all post_type='product' on 'solution'</p>\n\n<p>To fix 404 page, go to Settings->Permalinks and click Save Changes to refresh it.</p>\n"
},
{
"answer_id": 248203,
"author": "Daniel Mulder",
"author_id": 86859,
"author_profile": "https://wordpress.stackexchange.com/users/86859",
"pm_score": 0,
"selected": false,
"text": "<p>Myself I have not experienced this problem myself before but I would try to backtrack my steps and undo them. In that case I would think that you would have to unregister the new custom type Solutions and set the slug for the WC custom post type back to product again. For setting the slug for the WC products I would first try this via the normal Permalink options and set it to default and if this doesn’t do the trick I would also try setting it to this via the custom base permalink option for WC.</p>\n\n<p><strong>Step 1 unregister custom type</strong></p>\n\n<pre><code>// Function to unregister type\nif ( ! function_exists( 'unregister_post_type' ) ) :\nfunction unregister_post_type( $post_type ) {\n global $wp_post_types;\n if ( isset( $wp_post_types[ $post_type ] ) ) {\n unset( $wp_post_types[ $post_type ] );\n return true;\n }\n return false;\n}\nendif;\n\n\n// Unregister your new type solution\nunregister_post_type(‘solution’);\n</code></pre>\n\n<p>See <a href=\"https://wordpress.stackexchange.com/questions/3820/deregister-custom-post-types\">Deregister custom post types</a></p>\n\n<p><strong>Step 2 set permalink base products</strong> \nSet the permalink back to product for the WC base option.</p>\n\n<p>PS. Myself I don’t know the method to create a custom post type and move all existing WooCommerce products to populate your new custom post type Solutions. I’m stretching it here but I guess you are wanting to create a WooCommerce product type of your own and build for your specs? In that case I would approach it differently. I would use product attributes for creating extended features for most probably simple products type. These I would use to add custom meta info for each post like type, price class etc etc. Then you can use these to start all sorts of logic branching based on this information instead of creating a new type for what is actually an extensions of the product type anyway. </p>\n\n<p>I have created quite sophisticated features by only extending the product type using only product attributes ie for bookable products that are linked to Google Calendars and this for rental companies and boat trip companies etc. Both use the same basic product attributes from which I use the values in custom plug-in code. See this one ie which is almost finished. It uses product attributes for almost everything you can select <a href=\"http://kcd.meta-inc.com/\" rel=\"nofollow noreferrer\">http://kcd.meta-inc.com/</a>, or this one where the product attributes are used to link products (cars) to calendars and make search based on date and the realtime availability of the car in a Google calendar possible. <a href=\"http://huurauto-curacao.com/\" rel=\"nofollow noreferrer\">http://huurauto-curacao.com/</a> </p>\n\n<p>Or am I mistaking about what you are wanting to do? It needs to be pretty darn different or complex to need to is my opinion so that's why I’m really asking?</p>\n\n<p>Good luck and hope this helps. </p>\n"
},
{
"answer_id": 248306,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't tried this myself yet – and I would probably always prefer to go with the default 'products' for compatibility reasons… However it should be very well possible to add your own CPT to WooCommerce and then \"move\" all products to that new CPT. </p>\n\n<p>First you'll have to add a CPT to your WordPress installation that is compatible with WooCommerce so you can add things to the cart etc. Reigel Gallarde has written a step-by-step guide on how to do this: <a href=\"http://reigelgallarde.me/programming/how-to-add-custom-post-type-to-woocommerce/\" rel=\"nofollow noreferrer\">How to add custom post type to WooCommerce</a>.</p>\n\n<p>Then you could export all Products and import them as Solutions using the \n<a href=\"https://wordpress.org/plugins/ptypeconverter/\" rel=\"nofollow noreferrer\">pTypeConverter</a>.</p>\n\n<p>Don't forget to backup everything before you start!</p>\n"
},
{
"answer_id": 248346,
"author": "Marc",
"author_id": 71657,
"author_profile": "https://wordpress.stackexchange.com/users/71657",
"pm_score": 0,
"selected": false,
"text": "<p>Don't forget to reset your permalinks after adding/removing custom post types or you will get a 404 error when visiting the single pages. (Re-save them in your settings).</p>\n"
},
{
"answer_id": 248694,
"author": "LeeTee",
"author_id": 70019,
"author_profile": "https://wordpress.stackexchange.com/users/70019",
"pm_score": 1,
"selected": true,
"text": "<p>Looks like slugs have to be unique for all posts according to wordpress documentation.</p>\n\n<blockquote>\n <p>Post slugs must be unique across all posts</p>\n</blockquote>\n\n<p>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.</p>\n\n<p>Thanks for your help guys.</p>\n"
}
] |
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 ) {\nif( ! is_admin() && $q->is_category() && $q->is_main_query() ) {\n $sticky_posts = get_option( 'sticky_posts' );\n //If there are sticky posts\n if( ! empty( $sticky_posts ) ) {\n $q->set( 'post__in', (array) $sticky_posts );\n }\n //If not\n else {\n $q->set( 'post__in', array(0) );\n }\n}\n} );\n</code></pre>\n"
},
{
"answer_id": 247901,
"author": "fmeaddons",
"author_id": 107871,
"author_profile": "https://wordpress.stackexchange.com/users/107871",
"pm_score": 1,
"selected": false,
"text": "<p>Use <strong>else</strong> statement for the <strong>no result found</strong></p>\n\n<pre><code><?php \nadd_action( 'pre_get_posts', function( \\WP_Query $q ) {\nif( ! is_admin() && $q->is_category() && $q->is_main_query() ) {\n $sticky_posts = get_option( 'sticky_posts' );\n if( ! empty( $sticky_posts ) ) {\n $q->set( 'post__in', (array) $sticky_posts );\n} else {\n\n echo \"No posts found\";\n\n}\n}\n} );\n?>\n</code></pre>\n"
}
] |
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 ) {\nif( ! is_admin() && $q->is_category() && $q->is_main_query() ) {\n $sticky_posts = get_option( 'sticky_posts' );\n //If there are sticky posts\n if( ! empty( $sticky_posts ) ) {\n $q->set( 'post__in', (array) $sticky_posts );\n }\n //If not\n else {\n $q->set( 'post__in', array(0) );\n }\n}\n} );\n</code></pre>\n"
},
{
"answer_id": 247901,
"author": "fmeaddons",
"author_id": 107871,
"author_profile": "https://wordpress.stackexchange.com/users/107871",
"pm_score": 1,
"selected": false,
"text": "<p>Use <strong>else</strong> statement for the <strong>no result found</strong></p>\n\n<pre><code><?php \nadd_action( 'pre_get_posts', function( \\WP_Query $q ) {\nif( ! is_admin() && $q->is_category() && $q->is_main_query() ) {\n $sticky_posts = get_option( 'sticky_posts' );\n if( ! empty( $sticky_posts ) ) {\n $q->set( 'post__in', (array) $sticky_posts );\n} else {\n\n echo \"No posts found\";\n\n}\n}\n} );\n?>\n</code></pre>\n"
}
] |
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', 'insert_custom_rules');\n\nadd_filter('query_vars', 'insert_custom_vars');\n\n\nfunction insert_custom_vars($vars){ \n\n $vars[] = 'main_page'; \n\n return $vars;\n\n}\n\nfunction insert_custom_rules($rules) {\n\n $newrules = array();\n\n $newrules=array(\n 'page-name/(.+)/?' => 'index.php?pagename=page-name&main_page=$matches[1]'\n );\n\n return $newrules + $rules;\n}\n</code></pre>\n\n<p>So, with the help of get_query_var() function, we can get value from url and use accordingly. In this way, we can get pretty URLs.</p>\n\n<p>Note: If you have more than one rule, write the ones having more variables first and then those having less. Please specify static content between variables in case of multiple.</p>\n"
},
{
"answer_id": 248449,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 0,
"selected": false,
"text": "<p>There are a lot of assumptions here but maybe you can clear those up. This assumes you made a CPT that could look like:</p>\n\n<pre><code>domain.com/page/class/english-pro\n</code></pre>\n\n<p>And converts it to </p>\n\n<pre><code>domain.com/page/class-english-pro\n</code></pre>\n\n<p>Either way. The URL is taking the params and modifying the query to show a page. CPT was added in here so this example could work for anyone out of the box. And the permalink rewrite was added to adjust, well, the permalink.</p>\n\n<p>I'm not going to say this is the answer but there are some things in here that might help you.</p>\n\n<pre><code><?php\n\nif ( ! class_exists( 'PrefixClassesRewrites' ) ) {\n\n class PrefixClassesRewrites {\n\n const POST_TYPE_SLUG = 'classes';\n\n function __invoke() {\n add_action( 'init', array ( $this, 'prefix__init' ) );\n add_action( 'init', array ( $this, 'prefix__init_cpt' ), 0 );\n add_action( 'pre_get_posts', array ( $this, 'prefix__pre_get_posts' ) );\n add_filter( 'post_type_link', array ( $this, 'prefix__pre_post_link' ), 3 );\n add_filter( 'post_link', array ( $this, 'prefix__pre_post_link' ), 3 );\n }\n\n /**\n * Register the custom post type.\n */\n public function prefix__init_cpt() {\n $rewrite = array (\n 'slug' => 'page/class', // get's closer but will end with / not -\n 'with_front' => false,\n 'pages' => true,\n 'feeds' => true,\n );\n\n register_post_type( static::POST_TYPE_SLUG, array (\n 'label' => __( 'Classes Post Type', 'text_domain' ),\n 'description' => __( 'Classes Post Type Description', 'text_domain' ),\n 'rewrite' => $rewrite,\n 'hierarchical' => false,\n 'public' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'menu_position' => 5,\n 'show_in_admin_bar' => true,\n 'show_in_nav_menus' => true,\n 'can_export' => true,\n 'has_archive' => true,\n 'exclude_from_search' => false,\n 'publicly_queryable' => true,\n 'capability_type' => 'page',\n ) );\n }\n\n /**\n * Add the rewrite rule and allow custom query params\n */\n public function prefix__init() {\n // custom query params that we check for later\n add_rewrite_tag( '%_page_class%', '_page_class' );\n add_rewrite_tag( '%_language%', '([a-zA-Z\\d\\-_+]+)' );\n add_rewrite_tag( '%_need%', '([a-zA-Z\\d\\-_+]+)' );\n\n // rewrite rule to transform the URL into params\n add_rewrite_rule( 'page/class-([a-zA-Z\\d\\-_+]+)-([a-zA-Z\\d\\-_+]+)?', 'index.php?_page_class=1&_language=$matches[1]&_need=$matches[2]', 'top' );\n\n flush_rewrite_rules(); // <-- for testing only | removed once the rewrite rules are in place\n }\n\n /**\n * Modify the query to convert our params to a custom post type pagename\n *\n * @param $query\n */\n public function prefix__pre_get_posts( $query ) {\n\n // Check for our custom query param. Really just a flag to do this\n if ( isset( $query->query_vars[ '_page_class' ] ) ) {\n\n // Convert the variables to a custom post type name.\n $name = implode( '-', array (\n $query->query_vars[ '_language' ],\n $query->query_vars[ '_need' ],\n ) );\n\n // Add the name and post_type to the query.\n $query->query_vars[ 'name' ] = $name;\n $query->query_vars[ 'post_type' ] = array ( static::POST_TYPE_SLUG );\n\n // Nothing else to do here.\n return;\n }\n }\n\n /**\n * Rewrite the permalink to match our setup.\n *\n * @param string $permalink\n * @param null|WP_Post $post\n * @param bool $leavename\n *\n * @return string\n */\n public function prefix__pre_post_link( $permalink = '', $post = null, $leavename = false ) {\n return str_replace( '/page/class/', '/page/class-', $permalink );\n }\n }\n\n $prefixClassesRewrites = new PrefixClassesRewrites();\n $prefixClassesRewrites(); // kick off the process\n}\n</code></pre>\n"
},
{
"answer_id": 248668,
"author": "Pipo",
"author_id": 54879,
"author_profile": "https://wordpress.stackexchange.com/users/54879",
"pm_score": 1,
"selected": true,
"text": "<p>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. </p>\n\n<p><strong>I am using a <code>wp_safe_redirect</code> to the url of the corresponding custom post type</strong>.</p>\n\n<p>For those interested in the solution, my form action is the <code>permalink</code> of a page created just for this (let's call it <em>class</em>).</p>\n\n<p>On this <em>class</em> page I have the following safe redirect:</p>\n\n<pre><code>// getting my variables from the url\n$language = get_query_var( '_language' );\n$need = get_query_var( '_need' );\n\n// redirecting to the corresponding custom post type url\nif( isset( $language ) && isset( $need ) ) {\n wp_safe_redirect( esc_url( home_url('/') ) .'class/'. $language .'-'. $need .'/', 301 );\n exit;\n} else {\n // if variables are not defined \n // redirect to home (or whatever page you want)\n wp_safe_redirect( esc_url( home_url('/') ) );\n exit;\n}\n</code></pre>\n\n<p>Now everything works great!</p>\n"
}
] |
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-post-type-permalinks</a>' plugin </p>\n\n<p>and insert '/%year%/%postname%/' to your custom post type text field it will show link like:</p>\n\n<pre><code> www.abc.com/university/2015/ali\n www.abc.com/university/2016/ali\n</code></pre>\n"
},
{
"answer_id": 248094,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 1,
"selected": false,
"text": "<p>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\nI am getting this 'www.abc.com/2016/projects/test-permalink/'.</p>\n\n<pre><code> add_filter( 'pre_get_posts', 'query_post_type' );\n function query_post_type( $query ) {\n if ( is_category() ) {\n $post_type = get_query_var( 'post_type' );\n if ( $post_type ) {\n $post_type = $post_type;\n } else { $post_type = array( 'nav_menu_item', 'post', 'projects' ); // End if().\n }\n $query->set( 'post_type',$post_type );\n return $query;\n }\n }\n\n function custom_post_type() {\n\n// Set UI labels for Custom Post Type\n$labels = array(\n 'name' => _x( 'projects', 'Post Type General Name', 'namo' ),\n 'singular_name' => _x( 'projects', 'Post Type Singular Name', 'namo' ),\n 'menu_name' => __( 'projects', 'textdomain' ),\n 'parent_item_colon' => __( 'Parent projects', 'textdomain' ),\n 'all_items' => __( 'All projects', 'textdomain' ),\n 'view_item' => __( 'View projects', 'textdomain' ),\n 'add_new_item' => __( 'Add New projects', 'textdomain' ),\n 'add_new' => __( 'Add New', 'textdomain' ),\n 'edit_item' => __( 'Edit projects', 'textdomain' ),\n 'update_item' => __( 'Update projects', 'textdomain' ),\n 'search_items' => __( 'Search projects', 'textdomain' ),\n 'not_found' => __( 'Not Found', 'textdomain' ),\n 'not_found_in_trash' => __( 'Not found in Trash', 'textdomain' ),\n);\n\n// Set other options for Custom Post Type\n\n$args = array(\n 'label' => __( 'projects', 'textdomain' ),\n 'description' => __( 'projects news and reviews', 'textdomain' ),\n 'labels' => $labels,\n 'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields' ),\n 'hierarchical' => false,\n 'public' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'show_in_nav_menus' => true,\n 'show_in_admin_bar' => true,\n 'menu_position' => 5,\n 'can_export' => true,\n 'has_archive' => true,\n 'exclude_from_search' => false,\n 'publicly_queryable' => true,\n 'capability_type' => 'page',\n 'rewrite' => array(\n 'slug' => '%project_category%/projects',\n 'with_front' => true,\n ),\n\n // This is where we add taxonomies to our CPT\n //'taxonomies' => array( 'category' ),\n);\n\n// Registering your Custom Post Type\nregister_post_type( 'projects', $args );\n// Add new taxonomy, NOT hierarchical (like tags)\n$labels = array(\n 'name' => _x( 'project_category', 'taxonomy general name', 'textdomain' ),\n 'singular_name' => _x( 'project_category', 'taxonomy singular name', 'textdomain' ),\n 'search_items' => __( 'Search project_categorys', 'textdomain' ),\n 'popular_items' => __( 'Popular project_categorys', 'textdomain' ),\n 'all_items' => __( 'All project_categorys', 'textdomain' ),\n 'parent_item' => null,\n 'parent_item_colon' => null,\n 'edit_item' => __( 'Edit project_category', 'textdomain' ),\n 'update_item' => __( 'Update project_category', 'textdomain' ),\n 'add_new_item' => __( 'Add New project_category', 'textdomain' ),\n 'new_item_name' => __( 'New project_category Name', 'textdomain' ),\n 'separate_items_with_commas' => __( 'Separate project_category with commas', 'namo' ),\n 'add_or_remove_items' => __( 'Add or remove project_category', 'namo' ),\n 'choose_from_most_used' => __( 'Choose from the most used project_category', 'namo' ),\n 'not_found' => __( 'No project_category found.', 'namo' ),\n 'menu_name' => __( 'project_category', 'namo' ),\n);\n\n$args1 = array(\n 'hierarchical' => false,\n 'labels' => $labels,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'update_count_callback' => '_update_post_term_count',\n 'query_var' => true,\n //'rewrite' => array( 'slug' => 'project_category' ),\n 'rewrite' => array(\n 'slug' => 'project_category',\n 'with_front' => true,\n ),\n );\n register_taxonomy( 'project_category', 'projects', $args1 );\n\n }\n\n\n\n add_action( 'init', 'custom_post_type', 0 );\n\n\n function so23698827_add_rewrite_rules( $rules ) {\n $new = array();\n $new['([^/]+)/(.+)/?$/projects'] = 'index.php?projects=$matches[2]';\n $new['(.+)/?$/projects'] = 'index.php?project_category=$matches[1]';\n\n return array_merge( $new, $rules ); // Ensure our rules come first\n }\n add_filter( 'rewrite_rules_array', 'so23698827_add_rewrite_rules' );\n\n\n function so23698827_filter_post_type_link( $link, $post ) {\n if ( $post->post_type == 'projects' ) {\n if ( $cats = get_the_terms( $post->ID, 'project_category' ) ) {\n $link = str_replace( '%project_category%', current( $cats )->slug, $link );\n }\n }\n return $link;\n } \n add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );\n</code></pre>\n"
}
] |
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, 'fieldname', $value);\nupdate_post_meta($post_id, '_fieldname', 'field_' . uniqid()); // `uniqid() is a native PHP function. This is also how ACF creates the field keys\n</code></pre>\n\n<p>Also, depending where you are retrieving the value, you may also have to pass the post id.</p>\n\n<pre><code>the_field('fieldname', $post_id);\n</code></pre>\n"
},
{
"answer_id": 248010,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 0,
"selected": false,
"text": "<p>use following to retrieve ACF field values:</p>\n\n<pre><code> get_field('fieldname',$post_id);\n</code></pre>\n"
},
{
"answer_id": 248013,
"author": "Grzegorz",
"author_id": 108073,
"author_profile": "https://wordpress.stackexchange.com/users/108073",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up with following, which works for me:</p>\n\n<pre><code>function edu_acf_getValue($fieldname, $post_id = false){\n if($post_id === false) $post_id = get_the_ID ();\n if(($value = get_field($fieldname, $post_id)))\n return $value;\n $value = get_post_meta($post_id, $fieldname);\n return $value[0];\n}\nfunction edu_acf_updateValue($fieldname, $value, $post_id){\n $field_key = 'field_' . uniqid();\n update_post_meta($post_id, $fieldname, $value);\n update_post_meta($post_id, '_'.$fieldname, $field_key);\n update_field($field_key, $value, $post_id);\n}\n</code></pre>\n"
}
] |
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, 'fieldname', $value);\nupdate_post_meta($post_id, '_fieldname', 'field_' . uniqid()); // `uniqid() is a native PHP function. This is also how ACF creates the field keys\n</code></pre>\n\n<p>Also, depending where you are retrieving the value, you may also have to pass the post id.</p>\n\n<pre><code>the_field('fieldname', $post_id);\n</code></pre>\n"
},
{
"answer_id": 248010,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 0,
"selected": false,
"text": "<p>use following to retrieve ACF field values:</p>\n\n<pre><code> get_field('fieldname',$post_id);\n</code></pre>\n"
},
{
"answer_id": 248013,
"author": "Grzegorz",
"author_id": 108073,
"author_profile": "https://wordpress.stackexchange.com/users/108073",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up with following, which works for me:</p>\n\n<pre><code>function edu_acf_getValue($fieldname, $post_id = false){\n if($post_id === false) $post_id = get_the_ID ();\n if(($value = get_field($fieldname, $post_id)))\n return $value;\n $value = get_post_meta($post_id, $fieldname);\n return $value[0];\n}\nfunction edu_acf_updateValue($fieldname, $value, $post_id){\n $field_key = 'field_' . uniqid();\n update_post_meta($post_id, $fieldname, $value);\n update_post_meta($post_id, '_'.$fieldname, $field_key);\n update_field($field_key, $value, $post_id);\n}\n</code></pre>\n"
}
] |
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, 'fieldname', $value);\nupdate_post_meta($post_id, '_fieldname', 'field_' . uniqid()); // `uniqid() is a native PHP function. This is also how ACF creates the field keys\n</code></pre>\n\n<p>Also, depending where you are retrieving the value, you may also have to pass the post id.</p>\n\n<pre><code>the_field('fieldname', $post_id);\n</code></pre>\n"
},
{
"answer_id": 248010,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 0,
"selected": false,
"text": "<p>use following to retrieve ACF field values:</p>\n\n<pre><code> get_field('fieldname',$post_id);\n</code></pre>\n"
},
{
"answer_id": 248013,
"author": "Grzegorz",
"author_id": 108073,
"author_profile": "https://wordpress.stackexchange.com/users/108073",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up with following, which works for me:</p>\n\n<pre><code>function edu_acf_getValue($fieldname, $post_id = false){\n if($post_id === false) $post_id = get_the_ID ();\n if(($value = get_field($fieldname, $post_id)))\n return $value;\n $value = get_post_meta($post_id, $fieldname);\n return $value[0];\n}\nfunction edu_acf_updateValue($fieldname, $value, $post_id){\n $field_key = 'field_' . uniqid();\n update_post_meta($post_id, $fieldname, $value);\n update_post_meta($post_id, '_'.$fieldname, $field_key);\n update_field($field_key, $value, $post_id);\n}\n</code></pre>\n"
}
] |
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 replace, after the database has been backed up of course. </p>\n\n<p>Before learning more about SQL, I used this: <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a>, 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.</p>\n\n<p>Don't forget to delete it after using it though, if you do use it!</p>\n"
},
{
"answer_id": 248429,
"author": "physalis",
"author_id": 25245,
"author_profile": "https://wordpress.stackexchange.com/users/25245",
"pm_score": 0,
"selected": false,
"text": "<p>Since you asked for a plugin solution, which by the way is the most convenient way as opposed to using direct database search/regex, this is what I use on all of my projects for going easily from staging to production:</p>\n\n<p><a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/search-and-replace/</a></p>\n\n<p>You can easily run a test search for your query (so you don't need to make changes on the fly), export your changes as an .SQL file or change the database entries directly. I never encountered any errors, plus support/development for the plugin are most likely to be maintained with this plugin ;).</p>\n"
}
] |
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 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.</p>\n\n<p>I'd look into <a href=\"https://wordpress.org/plugins/wp-migrate-db/\" rel=\"nofollow noreferrer\">WP Migrate DB</a> to be able to pull in your site (or just your posts). However, you could simply <a href=\"https://wordpress.org/plugins/wordpress-importer/\" rel=\"nofollow noreferrer\">import</a> your old posts into a fresh install of Wordpress and go from there.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 248070,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>you could use the same database, but just change the prefix. This would of course require you to copy the entire database (all tables) with prefix change into the same database.</p>\n\n<p>I don't suggest that though. It would be easier (and safer so you don't mess with production) to download a copy of the database sql and upload this into a new database all together. This keeps files separate as well if you make any changes as part of the update. Then there is less chance of messing up production, plus when you're ready to go live you keep dev and live separate. These are all good things.</p>\n\n<p>Here's what I would do:</p>\n\n<p>create a subdomain for your site. if your site is www.example.com. make it dev.example.com</p>\n\n<p>Copy your entire www directory into the subdomain directory that you created when you created the subdomain. (www/dev for example)</p>\n\n<p>Now create a new database (you can use the same user so pw will stay the same).</p>\n\n<p>in your dev directory in wp-config.php change the line for your dbname to the new database you just created. If you gave the same user permissions on this database you won't have to change dbuser or dbpw.</p>\n\n<p>Make sure you've copied the database content from one database to the next. Easiest way to do this is phpmyadmin. Open the original database and at the top choose export. save as SQL. Now open the new database in phpmyadmin and at the top choose import. Find the sql file you just downloaded from the original live site and upload it here. </p>\n\n<p>Now go get this tool:\n<a href=\"http://search%20and%20replace%20db\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a></p>\n\n<p>Upload into your www/dev folder. (i usually rename the search and replace folder to SRDB.)</p>\n\n<p>now navigate to dev.example.com/SRDB and the top two lines you'll see a search field and a replace field. in the search place your live site address:\nwww.example.com</p>\n\n<p>in the replace field place your dev url:\ndev.example.com</p>\n\n<p>hit live live run. ONLY do this after ensuring your on your dev url and that it's loaded into your dev database.</p>\n\n<p>After this runs it's course, you'll have successfully backed up your site, database and have a functioning dev site to mess with that won't mess with your live site.</p>\n\n<p>As a side note. If you can avoid running live and dev on the same server, i usually recommend that just to avoid confusion and to note that if you have any backup programs running on your live site it may include the new dev folder in the backup if you don't exclude it from the back up.</p>\n"
}
] |
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 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 </p>\n\n<pre><code> register_taxonomy(\n 'works_category', \n 'works', \n array(\n 'hierarchical' => true, \n 'label' => 'Works Category', \n 'query_var' => 'works_category', \n 'rewrite' => array('slug' => 'works-categorys')\n )\n );\n</code></pre>\n\n<p>Or just suppress query_var from the array ?</p>\n"
},
{
"answer_id": 384809,
"author": "Fanky",
"author_id": 89973,
"author_profile": "https://wordpress.stackexchange.com/users/89973",
"pm_score": 0,
"selected": false,
"text": "<p>The reason for this might be also that someone's 'capabilities' in register_taxonomy aren't set right. These define management privileges based on post management capabilities:</p>\n<pre><code>register_taxonomy('mycat', 'mycustomtype',\n array(\n //...,\n 'capabilities' => array(\n 'manage_terms' => 'manage_categories',\n 'edit_terms' => 'manage_categories',\n 'delete_terms' => 'manage_categories',\n 'assign_terms' => 'edit_posts'\n )\n )\n);\n</code></pre>\n"
}
] |
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 showing just to check if your theme is overriding your code. </p>\n"
},
{
"answer_id": 309569,
"author": "Brian Cheong",
"author_id": 147573,
"author_profile": "https://wordpress.stackexchange.com/users/147573",
"pm_score": 0,
"selected": false,
"text": "<p>The solution is include to <code><!DOCTYPE html></code> in your html file. By the way, I do not know the exact reason that Safari requires doctype.</p>\n"
}
] |
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 showing just to check if your theme is overriding your code. </p>\n"
},
{
"answer_id": 309569,
"author": "Brian Cheong",
"author_id": 147573,
"author_profile": "https://wordpress.stackexchange.com/users/147573",
"pm_score": 0,
"selected": false,
"text": "<p>The solution is include to <code><!DOCTYPE html></code> in your html file. By the way, I do not know the exact reason that Safari requires doctype.</p>\n"
}
] |
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 showing just to check if your theme is overriding your code. </p>\n"
},
{
"answer_id": 309569,
"author": "Brian Cheong",
"author_id": 147573,
"author_profile": "https://wordpress.stackexchange.com/users/147573",
"pm_score": 0,
"selected": false,
"text": "<p>The solution is include to <code><!DOCTYPE html></code> in your html file. By the way, I do not know the exact reason that Safari requires doctype.</p>\n"
}
] |
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><code>CREATE TABLE wp_postmeta (\n meta_id bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n post_id bigint(20) unsigned NOT NULL DEFAULT '0',\n meta_key varchar(255) DEFAULT NULL,\n meta_value longtext,\n PRIMARY KEY (meta_id),\n KEY post_id (post_id),\n KEY meta_key (meta_key)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n</code></pre>\n\n<p>The problems: </p>\n\n<ul>\n<li>The <code>AUTO_INCREMENT</code> 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) </li>\n<li>The <code>AUTO_INCREMENT</code> is extra clutter - both on disk and in cache. </li>\n<li>Much better is <code>PRIMARY KEY(post_id, meta_key)</code> -- clustered, handles both parts of usual <code>JOIN</code>. </li>\n<li><code>BIGINT</code> is overkill, but that can't be fixed without changing other tables. </li>\n<li><code>VARCHAR(255)</code> can be a problem in MySQL 5.6 with <code>utf8mb4</code>; see workarounds below. </li>\n<li>When would meta_key or meta_value ever be <code>NULL</code>? </li>\n</ul>\n\n<p>The solutions: </p>\n\n<pre><code>CREATE TABLE wp_postmeta (\n post_id BIGINT UNSIGNED NOT NULL,\n meta_key VARCHAR(255) NOT NULL,\n meta_value LONGTEXT NOT NULL,\n PRIMARY KEY(post_id, meta_key),\n INDEX(meta_key)\n ) ENGINE=InnoDB;\n</code></pre>\n\n<p>The typical usage: </p>\n\n<pre><code>JOIN wp_postmeta AS m ON p.id = m.post_id\nWHERE m.meta_key = '...'\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>The composite <code>PRIMARY KEY</code> goes straight to the desired row, no digression through secondary index, nor search through multiple rows. </li>\n<li><code>INDEX(meta_key)</code> may or may not be useful, depending on what other queries you have. </li>\n<li>InnoDB is required for the 'clustering'. </li>\n<li>Going forward, use utf8mb4, not utf8. However, you should be consistent across all WP tables and in your connection parameters. </li>\n</ul>\n\n<p>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: </p>\n\n<ul>\n<li>Upgrade to 5.7.7 for 3072 byte limit -- your cloud may not provide this; </li>\n<li>Change 255 to 191 on the VARCHAR -- you lose any keys longer than 191 characters (unlikely?); </li>\n<li>ALTER .. CONVERT TO utf8 -- you lose Emoji and some of Chinese; </li>\n<li>Use a \"prefix\" index -- you lose some of the performance benefits; </li>\n<li>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. </li>\n</ul>\n\n<p><strong>Potential incompatibilities</strong></p>\n\n<ul>\n<li><code>meta_id</code> is probably not used anywhere. (But it is a risk to remove it).</li>\n<li>You could keep <code>meta_id</code> and get most of the benefits by changing to these indexes: <code>PRIMARY KEY(post_id, meta_key, meta_id), INDEX(meta_id), INDEX(meta_key, post_id)</code>. (Note: By having <code>meta_id</code> on the end of the PK, it is possible for post_id+meta_key to be non-unique.)</li>\n<li>Changing from <code>BIGINT</code> to a smaller datatype would involve changing other tables, too.</li>\n</ul>\n\n<p><strong>utf8mb4</strong></p>\n\n<ul>\n<li>Moving to 5.7 should not be incompatible.</li>\n<li>Shrinking to <code>VARCHAR(191)</code> would require the user to understand that the limit is now the arbitrary \"191\" instead of the previous arbitrary limit of \"255\".</li>\n<li>The 'reconfigure' fix is DBA issues, not incompatibility issues.</li>\n</ul>\n\n<p><strong>Comment</strong></p>\n\n<p>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.</p>\n\n<p>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 <em>MySQL</em> issues they are having.</p>\n\n<p>Taken from Rick James mysql blog: <a href=\"http://mysql.rjweb.org/doc.php/index_cookbook_mysql#speeding_up_wp_postmeta\" rel=\"nofollow noreferrer\">source</a></p>\n"
},
{
"answer_id": 280972,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>If you are looking for DB performance \"out of the box\", then the post meta table is the wrong place to store things that you will want to search for. The way you describe your query it will be much better to use a taxonomy for that usage case.</p>\n\n<p>But if you are already too much \"down the rabbit hole\" to restructure your DB, you should look into caching solution, which might not help with speeding up the query, but with good caching you will suffer the delay only once. Use cron to generate the cache when needed, and there will be zero noticeable user impact.</p>\n"
}
] |
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 [email protected] --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>Found it <a href=\"https://wordpress.stackexchange.com/a/193085\" title=\"here\">here</a></p>\n"
},
{
"answer_id": 331550,
"author": "Riordan Hanly",
"author_id": 163081,
"author_profile": "https://wordpress.stackexchange.com/users/163081",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an old question, but I found this while looking for a similar solution. Best solution (unless you alter the DB directly) seems to be the --prompt argument.\nYou can pass the new password over stdin with</p>\n\n<pre><code>wp user update <USER> --prompt=user_pass\n</code></pre>\n\n<p>This avoids having the PW show up in your history/process list.</p>\n"
},
{
"answer_id": 364582,
"author": "Koubi",
"author_id": 186320,
"author_profile": "https://wordpress.stackexchange.com/users/186320",
"pm_score": 3,
"selected": true,
"text": "<p>There is not \"one command\" in Wordpress CLI that does the job: <a href=\"https://github.com/wp-cli/wp-cli/issues/2270\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/wp-cli/issues/2270</a></p>\n\n<p>However using other commands, you can overide the user password directly in the database using the following:</p>\n\n<pre><code>USER_ID=$(wp user list --login=\"$USR_LOGIN\" --format=ids)\nwp db query \"UPDATE wp_users SET user_pass='$HASHED_PASS' WHERE ID = $USER_ID;\"\n</code></pre>\n\n<p>First line is optional if you already know the user ID.</p>\n\n<p>To hash a password, use the following:</p>\n\n<pre><code>wp eval \"echo wp_hash_password('$CLEAR_PASSWORD');\"\n</code></pre>\n"
}
] |
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 [email protected] --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 code</p>\n"
},
{
"answer_id": 248281,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": true,
"text": "<p>You can do it like this in admin section-</p>\n\n<pre><code>add_action( 'admin_init', 'redirect_non_logged_users_to_specific_page' );\n\nfunction redirect_non_logged_users_to_specific_page() {\n\n if ( !is_user_logged_in() && is_page('add page slug or i.d here') && \n $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {\n\n wp_redirect( 'http://www.example.dev/page/' ); \n exit;\n}\n</code></pre>\n\n<p>And for frontend-</p>\n\n<pre><code>add_action( 'template_redirect', 'redirect_to_specific_page' );\n\nfunction redirect_to_specific_page() {\n\n if ( is_page('slug') && ! is_user_logged_in() ) {\n\n wp_redirect( 'http://www.example.dev/your-page/', 301 );\n exit;\n }\n}\n</code></pre>\n\n<p>And this <code>auth_redirect</code> function is for backend. If you want to use it on front end then add the below filter-</p>\n\n<pre><code>add_filter( 'auth_redirect_scheme', 'the_dramatistcheck_loggedin' );\nfunction the_dramatist_check_loggedin(){\n return 'logged_in';\n}\n</code></pre>\n\n<p>Then <code>auth_redirect()</code> will work as expected : redirect users to the login form if they are not logged in.</p>\n"
}
] |
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> arguments (<em>PHP 5.4+</em>):</p>\n\n<pre><code>wp_get_archives(\n [\n 'before' => '<span>',\n 'after' => '</span>'\n ]\n);\n</code></pre>\n\n<p>if you want to wrap the <code><span></code> tag around the <code><a></code> tag:</p>\n\n<pre><code><li><span><a href=\"xx\">Link text</a></span></li>\n</code></pre>\n\n<h2>Span inside anchor tags</h2>\n\n<p>If you want it inside the anchor tags:</p>\n\n<pre><code><li><a href=\"xx\"><span>Link text</span></a></li>\n</code></pre>\n\n<p>then you could use the <code>get_archives_link</code> filter to reconstruct the links to your needs.</p>\n\n<p>Modify the corresponding theme file with (<em>PHP 5.4+</em>):</p>\n\n<pre><code>// Add a custom filter\nadd_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );\n\n// Archive\nwp_get_archives(\n [\n 'type' => 'yearly', // For yearly archive\n 'format' => 'html' // This is actually a default setting\n ]\n); // EDIT the arguments to your needs (I'm not showing the <ul> part here)\n\n// Remove the custom filter\nremove_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );\n</code></pre>\n\n<p>where our filter callback is defined, in the <code>functions.php</code> file in the current theme directory, as:</p>\n\n<pre><code>function wpse_get_archives_link( $link_html, $url, $text, $format, $before, $after )\n{\n if( 'html' === $format )\n $link_html = \"\\t<li>$before<a href='$url'><span>$text</span></a>$after</li>\\n\";\n\n return $link_html;\n}\n</code></pre>\n\n<p>where we've added the span inside the anchor tag.</p>\n"
},
{
"answer_id": 248403,
"author": "Shashank Sharma",
"author_id": 108381,
"author_profile": "https://wordpress.stackexchange.com/users/108381",
"pm_score": -1,
"selected": false,
"text": "<p>You can use custom query to modify html or add span</p>\n\n<pre><code>SELECT COUNT(ID) posts, YEAR(post_date) y, MONTH(post_date) m \n FROM $wpdb->posts \n WHERE post_status = 'publish'\nGROUP BY y, m\n HAVING y = YEAR(NOW())\nUNION\n SELECT COUNT(ID), YEAR(post_date) y, 0\n FROM $wpdb->posts\n WHERE post_status = 'publish'\nGROUP BY y\n HAVING y < YEAR(NOW())\nORDER BY y DESC, m DESC;\n</code></pre>\n"
}
] |
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> arguments (<em>PHP 5.4+</em>):</p>\n\n<pre><code>wp_get_archives(\n [\n 'before' => '<span>',\n 'after' => '</span>'\n ]\n);\n</code></pre>\n\n<p>if you want to wrap the <code><span></code> tag around the <code><a></code> tag:</p>\n\n<pre><code><li><span><a href=\"xx\">Link text</a></span></li>\n</code></pre>\n\n<h2>Span inside anchor tags</h2>\n\n<p>If you want it inside the anchor tags:</p>\n\n<pre><code><li><a href=\"xx\"><span>Link text</span></a></li>\n</code></pre>\n\n<p>then you could use the <code>get_archives_link</code> filter to reconstruct the links to your needs.</p>\n\n<p>Modify the corresponding theme file with (<em>PHP 5.4+</em>):</p>\n\n<pre><code>// Add a custom filter\nadd_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );\n\n// Archive\nwp_get_archives(\n [\n 'type' => 'yearly', // For yearly archive\n 'format' => 'html' // This is actually a default setting\n ]\n); // EDIT the arguments to your needs (I'm not showing the <ul> part here)\n\n// Remove the custom filter\nremove_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );\n</code></pre>\n\n<p>where our filter callback is defined, in the <code>functions.php</code> file in the current theme directory, as:</p>\n\n<pre><code>function wpse_get_archives_link( $link_html, $url, $text, $format, $before, $after )\n{\n if( 'html' === $format )\n $link_html = \"\\t<li>$before<a href='$url'><span>$text</span></a>$after</li>\\n\";\n\n return $link_html;\n}\n</code></pre>\n\n<p>where we've added the span inside the anchor tag.</p>\n"
},
{
"answer_id": 248403,
"author": "Shashank Sharma",
"author_id": 108381,
"author_profile": "https://wordpress.stackexchange.com/users/108381",
"pm_score": -1,
"selected": false,
"text": "<p>You can use custom query to modify html or add span</p>\n\n<pre><code>SELECT COUNT(ID) posts, YEAR(post_date) y, MONTH(post_date) m \n FROM $wpdb->posts \n WHERE post_status = 'publish'\nGROUP BY y, m\n HAVING y = YEAR(NOW())\nUNION\n SELECT COUNT(ID), YEAR(post_date) y, 0\n FROM $wpdb->posts\n WHERE post_status = 'publish'\nGROUP BY y\n HAVING y < YEAR(NOW())\nORDER BY y DESC, m DESC;\n</code></pre>\n"
}
] |
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> arguments (<em>PHP 5.4+</em>):</p>\n\n<pre><code>wp_get_archives(\n [\n 'before' => '<span>',\n 'after' => '</span>'\n ]\n);\n</code></pre>\n\n<p>if you want to wrap the <code><span></code> tag around the <code><a></code> tag:</p>\n\n<pre><code><li><span><a href=\"xx\">Link text</a></span></li>\n</code></pre>\n\n<h2>Span inside anchor tags</h2>\n\n<p>If you want it inside the anchor tags:</p>\n\n<pre><code><li><a href=\"xx\"><span>Link text</span></a></li>\n</code></pre>\n\n<p>then you could use the <code>get_archives_link</code> filter to reconstruct the links to your needs.</p>\n\n<p>Modify the corresponding theme file with (<em>PHP 5.4+</em>):</p>\n\n<pre><code>// Add a custom filter\nadd_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );\n\n// Archive\nwp_get_archives(\n [\n 'type' => 'yearly', // For yearly archive\n 'format' => 'html' // This is actually a default setting\n ]\n); // EDIT the arguments to your needs (I'm not showing the <ul> part here)\n\n// Remove the custom filter\nremove_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );\n</code></pre>\n\n<p>where our filter callback is defined, in the <code>functions.php</code> file in the current theme directory, as:</p>\n\n<pre><code>function wpse_get_archives_link( $link_html, $url, $text, $format, $before, $after )\n{\n if( 'html' === $format )\n $link_html = \"\\t<li>$before<a href='$url'><span>$text</span></a>$after</li>\\n\";\n\n return $link_html;\n}\n</code></pre>\n\n<p>where we've added the span inside the anchor tag.</p>\n"
},
{
"answer_id": 248403,
"author": "Shashank Sharma",
"author_id": 108381,
"author_profile": "https://wordpress.stackexchange.com/users/108381",
"pm_score": -1,
"selected": false,
"text": "<p>You can use custom query to modify html or add span</p>\n\n<pre><code>SELECT COUNT(ID) posts, YEAR(post_date) y, MONTH(post_date) m \n FROM $wpdb->posts \n WHERE post_status = 'publish'\nGROUP BY y, m\n HAVING y = YEAR(NOW())\nUNION\n SELECT COUNT(ID), YEAR(post_date) y, 0\n FROM $wpdb->posts\n WHERE post_status = 'publish'\nGROUP BY y\n HAVING y < YEAR(NOW())\nORDER BY y DESC, m DESC;\n</code></pre>\n"
}
] |
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 stored all category featured images in the <code>category_images</code> option. So you can use <code>get_option</code> to retrieve the featured image for each category:</p>\n\n<pre><code>$image_urls = get_option( 'category_images', array() ); \n\nforeach ( $categories as $category ) {\n $cat_id = $category->term_id;\n $image_url = isset( $image_urls[$cat_id ) ? $image_urls[$cat_id] : '';\n\n ...\n}\n</code></pre>\n\n<p>You can then use <code>$image_url</code> as the <code>src</code> attribute of an <code><img></code>.</p>\n\n<p><strong>How can I display only the subcategories of a certain category parent?</strong></p>\n\n<p>Like <code>get_terms</code>, <code>get_categories</code> has a 'child_of' parameter. Again, in your <code>foreach</code> loop:</p>\n\n<pre><code> $sub_categories = get_categories( array(\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'child_of' => $cat_id,\n ) );\n\n foreach ( $sub_categories as $sub_category ) {\n // Process the sub-categories here.\n }\n</code></pre>\n\n<p><strong>Is it possible to display these as a grid?</strong></p>\n\n<p>Yes, you can! But that's an <a href=\"https://stackoverflow.com/questions/tagged/css\">HTML/CSS question</a> 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. :)</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 260454,
"author": "Wordpress Novice",
"author_id": 115642,
"author_profile": "https://wordpress.stackexchange.com/users/115642",
"pm_score": 0,
"selected": false,
"text": "<p>I guess you've already found the answer. If you haven't, Use the function below.skip first category by using counter</p>\n\n<pre><code>function your_function( $taxonomy = 'category', $show_links = true, $echo = true ) {\n\n// Make sure taxonomy exists\nif ( ! taxonomy_exists( $taxonomy ) ) {\n return;\n}\n\n// Get terms\n$list_terms = array();\n$terms = wp_get_post_terms( get_the_ID(), $taxonomy );\n\n// Return if no terms are found\nif ( ! $terms ) {\n return;\n}\n\n// Loop through terms\nforeach ( $terms as $term ) {\n $permalink = get_term_link( $term->term_id, $taxonomy );\n if ( $show_links ) {\n $list_terms[] = '<a href=\"'. $permalink .'\" title=\"'. esc_attr( $term->name ) .'\" class=\"term-'. $term->term_id .'\">'. $term->name .'</a>';\n } else {\n $list_terms[] = '<span class=\"term-'. $term->term_id .'\">'. esc_attr( $term->name ) .'</span>';\n }\n}\n\n// Turn into comma seperated string\nif ( $list_terms && is_array( $list_terms ) ) {\n $list_terms = implode( ', ', $list_terms );\n} else {\n return;\n}\n\n// Echo terms\nif ( $echo ) {\n echo $list_terms;\n} else {\n return $list_terms;\n}\n</code></pre>\n\n<p>}</p>\n"
}
] |
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 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 <a href=\"https://developer.wordpress.org/themes/\" rel=\"nofollow noreferrer\">read about here</a>. The upside of being in the repository is that they will take care of pushing notifications to your users once new versions are available.</p>\n\n<p>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 (<a href=\"https://code.tutsplus.com/tutorials/a-guide-to-the-wordpress-http-api-automatic-plugin-updates--wp-25181\" rel=\"nofollow noreferrer\">example</a>).</p>\n\n<p><strong>Note</strong>: do not take for granted that all your users will automatically receive the new version, because <a href=\"https://codex.wordpress.org/Configuring_Automatic_Background_Updates#Plugin_.26_Theme_Updates_via_Filter\" rel=\"nofollow noreferrer\">they may have disabled updates</a>.</p>\n"
},
{
"answer_id": 264135,
"author": "JItendra Rana",
"author_id": 87433,
"author_profile": "https://wordpress.stackexchange.com/users/87433",
"pm_score": 0,
"selected": false,
"text": "<p>Refer to <a href=\"https://wordpress.stackexchange.com/questions/260969/update-my-custom-wordpress-plugin-through-my-own-server/260970#260970\">This Answer</a> !</p>\n\n<p>Try to avoid duplicate questions. Search before posting new question.</p>\n"
}
] |
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 <code>init</code> hook instead to \"boot up\" your plugin:</p>\n\n<pre><code>add_action( 'init', 'LocatorMap::init' );\n</code></pre>\n"
},
{
"answer_id": 374518,
"author": "iohnatan",
"author_id": 192590,
"author_profile": "https://wordpress.stackexchange.com/users/192590",
"pm_score": 2,
"selected": false,
"text": "<p>use the function <code>get_called_class()</code></p>\n<pre><code>public static function init() {\n add_action( 'wp_enqueue_scripts', array( get_called_class(), 'register_scripts' ) );\n}\n</code></pre>\n"
},
{
"answer_id": 391809,
"author": "Andrew Odri",
"author_id": 11379,
"author_profile": "https://wordpress.stackexchange.com/users/11379",
"pm_score": 2,
"selected": false,
"text": "<p>I recently had to do the same thing and ended up using the <a href=\"https://www.php.net/manual/en/language.oop5.late-static-bindings.php#language.oop5.late-static-bindings.usage\" rel=\"nofollow noreferrer\"><code>static::</code> late static binding</a> along with <a href=\"https://www.php.net/manual/en/language.oop5.constants.php#example-188\" rel=\"nofollow noreferrer\">special <code>::class</code> constant</a>. The <code>static::</code> binding will reference the calling class, while the <code>::class</code> constant will return a string that is the name of the calling class (with namespacing!)</p>\n<p>Using the example from the questiom, the implementation would like something like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>class LocatorMap {\n \n public static function init() {\n add_action( 'wp_enqueue_scripts', array( static::class, 'registerScripts' ) );\n }\n\n public function registerScripts() {}\n}\n</code></pre>\n<p>Since <code>static::</code> references the calling class, this allows to write reusable classes for your plugins/themes, and kind of wrap up some of WordPress' legacy ugliness.</p>\n<p>For example, you could write an abstract class for custom post types like this:</p>\n<pre><code>\nnamespace WordpressPlugin;\n\nabstract class AbstractPostType {\n const SLUG;\n\n private function __construct() {}\n\n public static function initialize() {\n add_action( 'init', array( static::class, 'registerPostType' ), 0 );\n add_action( 'init', array( static::class, 'registerTaxonomies' ), 1 );\n add_action( 'add_meta_boxes', array( static::class, 'addMetaBox' ) );\n }\n\n public static function registerPostType() {}\n\n public static function registerTaxonomies() {}\n\n public static function addMetaBox() {}\n}\n\n</code></pre>\n<p>Aftet that, you can now create custom post types without having to duplicate all of the boilerplate in each subclass, like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>namespace WordpressPlugin;\n\nclass ExamplePostType extends AbstractPostType {\n const SLUG = 'example-post-type';\n\n public static function registerPostType() {\n register_post_type( self::SLUG, array(\n ...\n ) );\n }\n}\n</code></pre>\n"
}
] |
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/includes/class-wp-posts-list-table.php#L918-L944\" rel=\"nofollow noreferrer\">hard-coded</a> and cannot be changed without changing the entire list table class:</p>\n\n<pre><code> $pad = str_repeat( '&#8212; ', $this->current_level );\n echo \"<strong>\";\n\n $format = get_post_format( $post->ID );\n if ( $format ) {\n $label = get_post_format_string( $format );\n\n $format_class = 'post-state-format post-format-icon post-format-' . $format;\n\n $format_args = array(\n 'post_format' => $format,\n 'post_type' => $post->post_type\n );\n\n echo $this->get_edit_link( $format_args, $label . ':', $format_class );\n }\n\n $can_edit_post = current_user_can( 'edit_post', $post->ID );\n $title = _draft_or_post_title();\n\n if ( $can_edit_post && $post->post_status != 'trash' ) {\n printf(\n '<a class=\"row-title\" href=\"%s\" aria-label=\"%s\">%s%s</a>',\n get_edit_post_link( $post->ID ),\n /* translators: %s: post title */\n esc_attr( sprintf( __( '&#8220;%s&#8221; (Edit)' ), $title ) ),\n $pad,\n $title\n );\n } else {\n echo $pad . $title;\n }\n</code></pre>\n\n<p>And even changing that table is very difficult, because the class instance is <a href=\"https://github.com/WordPress/WordPress/blob/88a72182ca1129f76c1abbf84725d0d01ddad93a/wp-admin/edit.php#L45\" rel=\"nofollow noreferrer\">set to a global variable</a> with the function <code>_get_list_table()</code>, which doesn't even offer a filter.</p>\n\n<p>Welcome to the wonderful world of procedural code.</p>\n\n<p>I guess you have to use JavaScript for that.</p>\n"
},
{
"answer_id": 248408,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 3,
"selected": true,
"text": "<p>You can't change dashes using any filter because there is no filter available to change it. </p>\n\n<p>but still you can change this using jQuery put this code inside functions.php</p>\n\n<pre><code>add_action('admin_head',function(){\n\n\nglobal $pagenow;\n\n// check current page.\nif( $pagenow == 'edit.php' ){ ?>\n\n <script>\n\n jQuery(function($){\n\n var post_title = $('.wp-list-table').find('a.row-title');\n $.each(post_title,function(index,em){\n var text = $(em).html();\n // Replace all dashes to * \n $(em).html(text.replace(/—/g ,'*'));\n });\n });\n\n </script>\n <?php\n }\n});\n</code></pre>\n\n<p>See <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/class-wp-posts-list-table.php#L918-L919\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/class-wp-posts-list-table.php#L918-L919</a></p>\n"
},
{
"answer_id": 248432,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>As @Toscho says, the title column is hard coded, so you cannot change that. What you can do, however, is remove the column and redefine it as a custom column:</p>\n\n<pre><code>add_filter( 'manage_pages_columns', 'wpse248405_columns', 25, 1 );\nfunction wpse248405_columns ($cols) {\n // remove title column\n unset( $cols['title'] );\n // add custom column in second place\n $cols = array('cb' => $cols['cb']) + array('title' => __( 'Title', 'textdomain' )) + $cols;\n // return columns\n return $cols;\n }\n</code></pre>\n\n<p>Now you have to make the custom column behave <a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-admin/includes/class-wp-posts-list-table.php#L862\" rel=\"nofollow noreferrer\">like the original</a>:</p>\n\n<pre><code>add_action( 'manage_pages_custom_column', 'wpse248405_custom_column', 10, 2 );\nfunction wpse248405_custom_column( $col, $post_id ) {\n if ($col == 'title') {\n $post = get_post( $post_id );\n $title = _draft_or_post_title();\n $can_edit_post = current_user_can( 'edit_post', $post->ID );\n // set up row actions\n $actions = array();\n if ( $can_edit_post && 'trash' != $post->post_status ) {\n $actions['title'] = '<strong><a href=\"' . get_edit_post_link( $post->ID, true ) . '\" aria-label=\"' . $title . esc_attr( __( 'Edit this item' ) ) . '\">' . $title . '</a></strong>';\n // invoke row actions\n $table = new WP_Posts_List_Table;\n echo $table->row_actions( $actions, true );\n }\n }\n }\n</code></pre>\n\n<p>Beware that if you mimick core behaviour in your own functions you become vulnerable to future core releases.</p>\n"
},
{
"answer_id": 286723,
"author": "webpager",
"author_id": 131969,
"author_profile": "https://wordpress.stackexchange.com/users/131969",
"pm_score": -1,
"selected": false,
"text": "<p>The dashes are because you have them listed under parent pages. Lower right side of the page edit screen you can remove the parents if you want or need to. </p>\n"
}
] |
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 some css to that class .</p>\n\n<p>other option may be enable sticky post in loop and than make your post sticky by editing from WordPress and assign css to that sticky article since that should have special class if it's created properly . </p>\n"
},
{
"answer_id": 248444,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Your question is a little short on detail, but let's suppose you have retrieved the posts using <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>wp_query</code></a> and are looping through it like this:</p>\n\n<pre><code>$the_query = new WP_Query( $args );\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n STUFF\n }\n wp_reset_postdata();\n } \n</code></pre>\n\n<p>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 <code>$current_post</code>, which holds the number of the post inside the loop. You would get this:</p>\n\n<pre><code>if ($the_query->current_post == 0) {\n // retrieve featured image, title and content }\nelse {\n // retrieve title only }\n</code></pre>\n"
}
] |
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 some css to that class .</p>\n\n<p>other option may be enable sticky post in loop and than make your post sticky by editing from WordPress and assign css to that sticky article since that should have special class if it's created properly . </p>\n"
},
{
"answer_id": 248444,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Your question is a little short on detail, but let's suppose you have retrieved the posts using <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>wp_query</code></a> and are looping through it like this:</p>\n\n<pre><code>$the_query = new WP_Query( $args );\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n STUFF\n }\n wp_reset_postdata();\n } \n</code></pre>\n\n<p>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 <code>$current_post</code>, which holds the number of the post inside the loop. You would get this:</p>\n\n<pre><code>if ($the_query->current_post == 0) {\n // retrieve featured image, title and content }\nelse {\n // retrieve title only }\n</code></pre>\n"
}
] |
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 search for <code>-</code>. </p>\n\n<pre><code>add_filter( 'posts_where', function( $where, $q )\n{ \n $where = str_replace( \"NOT LIKE '%%'\", \"LIKE '%-%'\", $where); \n return $where;\n\n}, 10, 2 );\n\n$args = array(\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 's' => '-'\n\n);\n\n$q = new WP_Query( $args );\nvar_dump($query->request);\n</code></pre>\n\n<p>The resulting query will be:</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID\nFROM wp_posts \nWHERE 1=1 \nAND (((wp_posts.post_title LIKE '%-%')\nAND (wp_posts.post_excerpt LIKE '%-%')\nAND (wp_posts.post_content LIKE '%-%'))) \nAND wp_posts.post_type = 'post'\nAND ((wp_posts.post_status = 'publish')) \nORDER BY wp_posts.post_date DESC\nLIMIT 0, 10\n</code></pre>\n"
},
{
"answer_id": 248563,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>One approach is to modify the <em>exclusion prefix</em> through the <a href=\"https://developer.wordpress.org/reference/hooks/wp_query_search_exclusion_prefix/\" rel=\"nofollow noreferrer\"><code>wp_query_search_exclusion_prefix</code></a> filter that's supported in WP 4.7+.\nSee ticket <a href=\"https://core.trac.wordpress.org/ticket/38099\" rel=\"nofollow noreferrer\">#38099</a>.</p>\n\n<p>Here's an example how we can change it from <code>-</code> to e.g. <code>!</code>:</p>\n\n<pre><code>add_filter( 'wp_query_search_exclusion_prefix', function( $prefix )\n{\n return '!'; // adjust to your needs (default is -)\n} );\n</code></pre>\n\n<p>where we would use <code>!apple</code> instead of <code>-apple</code> to exclude <code>apple</code> from the search results. Then you can search by <code>-</code>.</p>\n\n<p>It looks like the exclusion prefix must be a single character (or empty to disable this feature), because of this <a href=\"https://github.com/WordPress/WordPress/blob/16371b99d8e5111dcc83b8961b4d68681e82d25e/wp-includes/class-wp-query.php#L1335-L1344\" rel=\"nofollow noreferrer\">check in the core</a>:</p>\n\n<pre><code>// If there is an $exclusion_prefix, terms prefixed with it should be excluded.\n$exclude = $exclusion_prefix && ( $exclusion_prefix === substr( $term, 0, 1 ) );\nif ( $exclude ) {\n $like_op = 'NOT LIKE';\n $andor_op = 'AND';\n $term = substr( $term, 1 );\n} else {\n $like_op = 'LIKE';\n $andor_op = 'OR';\n}\n</code></pre>\n\n<p>Otherwise it sounds like a <strong>bug</strong>, not to be able to search only for the term exclusion prefix.</p>\n\n<p>I wonder if it would be better to add an extra <code>$exclusion_prefix !== $term</code> check to support that:</p>\n\n<pre><code>$exclude = $exclusion_prefix \n && $exclusion_prefix !== $term \n && ( $exclusion_prefix === mb_substr( $term, 0, 1 ) );\nif ( $exclude ) {\n $like_op = 'NOT LIKE';\n $andor_op = 'AND';\n $term = mb_substr( $term, 1 );\n} else {\n $like_op = 'LIKE';\n $andor_op = 'OR';\n}\n</code></pre>\n\n<p>where we would also use <code>mb_substr()</code> instead of <code>substr()</code> for a wider char support for the exclusion prefix.</p>\n\n<p>I guess I should just create ticket for this ...</p>\n"
}
] |
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 will work sort or less the same. You indeed need to use the __() or similar function but also you will always first need to load the text domain. I load the text domain straight after construction of the top class and is initiated explicitly by front and back-end controller descendants to spawn it so this and constants etc are always loaded before further functions execute. </p>\n\n<pre><code>/*\n* Init localization text domain\n*/\npublic static function plugin_load_textdomain(){\n load_plugin_textdomain( PLUGIN_TEXTDOMAIN, false, dirname( \n plugin_basename( __FILE__ ) ) . '/languages' ); \n}\n\n// This action hooks to WordPress init event and triggers it on init event\nadd_action( 'init', array($plugin->model, 'plugin_load_textdomain'), 10 ); \n</code></pre>\n\n<p>This should work similar with template functions I think. Then use it with a string to translate in view layer ie</p>\n\n<pre><code><?php echo __( 'Translate me!', PLUGIN_TEXTDOMAIN ); ?>\n</code></pre>\n\n<p>To make it work the folder plugin_basename( <strong>FILE</strong> ) ) . '/languages' must contain the PO files with the translated strings. I use Poedit for creating the files. The files created with Poedit are conform the native way WordPress translate and how MO works with WordPress is explained here <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/I18n_for_WordPress_Developers</a>. </p>\n\n<p>Hope this helps and I agree that good info is not much available on this. Feel free to ask more if needed! Gr</p>\n"
},
{
"answer_id": 248470,
"author": "Ollie",
"author_id": 104663,
"author_profile": "https://wordpress.stackexchange.com/users/104663",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<ol>\n<li>Create a folder in the root of your theme called \"languages\"</li>\n<li>Go to <a href=\"https://wpcentral.io/internationalization/\" rel=\"nofollow noreferrer\">https://wpcentral.io/internationalization/</a>, search for your language and copy the \"WordPress Locale\" code (e.g. cs_CZ for Czech)</li>\n<li>Open Poedit</li>\n<li>File -> New</li>\n<li>Paste the code you coped from wpcentral into the box that appears</li>\n<li>Press save, and save to the \"languages\" folder you created in step 1</li>\n<li>Press \"Extract from sources\" (or Catalogue->Properties)</li>\n<li>Under \"Sources Paths\" press the + on the Paths box</li>\n<li>Select your theme folder (e.g. wp-content/themes/my-theme)</li>\n<li>In the \"Sources Keywords\" tab, press \"New Item\"</li>\n<li>Type \"__\" (underscore underscore, no quotes), and press enter</li>\n<li>Type \"_e\" (no quotes), and press enter</li>\n<li>Press OK</li>\n<li>Press Save</li>\n<li>Press Catalogue->Update from sources</li>\n<li>You should see all translatable strings from your theme appear (basically any time you use \"__( 'Hello world', 'mydomain' )\", the translation will appear)</li>\n<li>Once you have completed your translations, press File->Compile to MO (save in the same languages folder from step 1)</li>\n<li><p>Add the following code to the top of your theme's functions file:</p>\n\n<pre><code>function mytheme_localisation(){\n\n function mytheme_localised( $locale ) {\n if ( isset( $_GET['l'] ) ) {\n return sanitize_key( $_GET['l'] );\n }\n return $locale;\n }\n add_filter( 'locale', 'mytheme_localised' );\n\n load_theme_textdomain( 'mytheme', get_template_directory() . '/languages' );\n}\nadd_action( 'after_setup_theme', 'mytheme_localisation' );\n</code></pre></li>\n<li>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)</li>\n</ol>\n\n<p>To summarise: to translate strings within your theme, use the following code:</p>\n\n<pre><code>__( 'Hello, World!', 'mytheme' )\n</code></pre>\n\n<p>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.</p>\n\n<p>I hope this helps someone else who has a similar problem, as this took me <em>ages</em> to figure out.</p>\n"
}
] |
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(event, variation_data) {\n //this is called when a valid productis found\n });\n jQuery(document).on('change.wc-variation-form', 'form.variations_form', function(event) {\n //this function is called when the user clicks or changes the dropdown\n });\n</code></pre>\n\n<p>The PHP function you are looking for is </p>\n\n<pre><code>apply_filters(\n 'woocommerce_available_variation',\n array(\n 'attributes' => $variation->get_variation_attributes(),\n 'availability_html' => wc_get_stock_html( $variation ),\n 'backorders_allowed' => $variation->backorders_allowed(),\n 'dimensions' => $variation->get_dimensions( false ),\n 'dimensions_html' => wc_format_dimensions( $variation->get_dimensions( false ) ),\n 'display_price' => wc_get_price_to_display( $variation ),\n 'display_regular_price' => wc_get_price_to_display( $variation, array( 'price' => $variation->get_regular_price() ) ),\n 'image' => wc_get_product_attachment_props( $variation->get_image_id() ),\n 'image_id' => $variation->get_image_id(),\n 'is_downloadable' => $variation->is_downloadable(),\n 'is_in_stock' => $variation->is_in_stock(),\n 'is_purchasable' => $variation->is_purchasable(),\n 'is_sold_individually' => $variation->is_sold_individually() ? 'yes' : 'no',\n 'is_virtual' => $variation->is_virtual(),\n 'max_qty' => 0 < $variation->get_max_purchase_quantity() ? $variation->get_max_purchase_quantity() : '',\n 'min_qty' => $variation->get_min_purchase_quantity(),\n 'price_html' => $show_variation_price ? '<span class=\"price\">' . $variation->get_price_html() . '</span>' : '',\n 'sku' => $variation->get_sku(),\n 'variation_description' => wc_format_content( $variation->get_description() ),\n 'variation_id' => $variation->get_id(),\n 'variation_is_active' => $variation->variation_is_active(),\n 'variation_is_visible' => $variation->variation_is_visible(),\n 'weight' => $variation->get_weight(),\n 'weight_html' => wc_format_weight( $variation->get_weight() ),\n ),\n $this,\n $variation\n );\n</code></pre>\n\n<p>This is found here <a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-product-variable.php#L325\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-product-variable.php#L325</a></p>\n\n<pre><code>WC_Product_Variable -> get_available_variation( $variation )\n</code></pre>\n"
},
{
"answer_id": 374406,
"author": "Jake",
"author_id": 169069,
"author_profile": "https://wordpress.stackexchange.com/users/169069",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry to be late to the party, but I needed something similar today. This is how I managed to get around it (<em>probably</em> not the most logical and efficient way).</p>\n<p>Firstly, you wouldn't want to use the <code>woocommerce_variation_has_changed</code> event, you'd need the <code>show_variation</code> as you can use the variation object there on a successful variation match. See <a href=\"https://stackoverflow.com/a/27849208/13347756\">this answer</a> for more information.</p>\n<p>As for adding data to the variation object, you can use the <code>woocommerce_available_variation</code> filter.</p>\n<pre><code>add_filter( 'woocommerce_available_variation', 'add_variation_data', 10, 3 );\nfunction add_variation_data( $array, $instance, $variation ){\n $array['custom_data_key'] = get_post_meta( $array['variation_id'], '_meta_key', true );\n return $array;\n}\n</code></pre>\n<p>This will now show inside the variation object when calling the <code>show_variation</code> event.</p>\n<p>Hope this helps.</p>\n"
}
] |
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 <a href=\"https://developer.jetpack.com/hooks/jetpack_get_available_modules/\" rel=\"nofollow noreferrer\"><code>jetpack_get_available_modules</code></a>, 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':</p>\n\n<pre><code>function wpse248480_filter_jetpack( $modules, $min_version, $max_version ) {\n if (!(in_array('sharedaddy',$modules))) $modules[] = 'sharedaddy';\n return $modules;\n }\nadd_filter( 'jetpack_get_available_modules', 'wpse248480_filter_jetpack', 20, 3 );\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>The above only filters the available modules. To actually (de)activate them programmatically use (<a href=\"https://github.com/Automattic/jetpack/blob/master/class.jetpack.php#L2478\" rel=\"nofollow noreferrer\">source</a>):</p>\n\n<pre><code>function wpse248480_activate_jetpack () {\n Jetpack::activate_module('sharedaddy');\n // Jetpack::deactivate_module('sharedaddy');\n }\nadd_action('after_setup_theme','wpse248480_activate_jetpack');\n</code></pre>\n"
},
{
"answer_id": 304089,
"author": "tom_mcc",
"author_id": 81502,
"author_profile": "https://wordpress.stackexchange.com/users/81502",
"pm_score": 1,
"selected": false,
"text": "<p>There is an official filter, <code>jetpack_active_modules</code>, for this now. It will force enable/disable modules as needed.</p>\n\n<p>Here is an example that will disable everything, and uncommenting a line will enable that module. In your case, you could simply make sure the string describing your desired module is present in the array before returning it.</p>\n\n<pre><code>function wpse248480_jetpack_active_modules( $active ) {\n $active = array(\n // 'after-the-deadline',\n // 'carousel',\n // 'comment-likes',\n // 'comments',\n // 'contact-form',\n // 'custom-content-types',\n // 'custom-css',\n // 'enhanced-distribution',\n // 'google-analytics',\n // 'gravatar-hovercards',\n // 'infinite-scroll',\n // 'json-api',\n // 'latex',\n // 'lazy-images',\n // 'likes',\n // 'manage',\n // 'markdown',\n // 'masterbar',\n // 'minileven',\n // 'module-extras',\n // 'module-headings',\n // 'module-info',\n // 'monitor',\n // 'notes',\n // 'photon',\n // 'post-by-email',\n // 'protect',\n // 'publicize',\n // 'pwa',\n // 'related-posts',\n // 'search',\n // 'seo-tools',\n // 'sharedaddy',\n // 'shortcodes',\n // 'shortlinks',\n // 'sitemaps',\n // 'sso',\n // 'stats',\n // 'subscriptions',\n // 'theme-tools',\n // 'tiled-gallery',\n // 'vaultpress',\n // 'verification-tools',\n // 'videopress',\n // 'widget-visibility',\n // 'widgets',\n // 'wordads',\n // 'wpgroho.js',\n );\n\n return $active;\n}\n\nadd_filter( 'jetpack_active_modules', 'wpse248480_jetpack_active_modules' );\n</code></pre>\n"
}
] |
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 <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect\" rel=\"nofollow noreferrer\">Codex</a> )</p>\n\n<pre><code>function redirect_users_by_role( $redirect_to, $request, $user ) {\n\n if ( isset( $user->roles ) && is_array( $user->roles ) ) {\n\n if ( in_array( 'staff', $user->roles ) ) {\n\n if ($admin_url === $request){\n\n return home_url('/resources');\n\n } else{\n\n return $redirect_to;\n\n }\n\n }\n } else {\n\n return home_url('/access-denied');\n\n }\n}\n\n\nadd_filter( 'login_redirect', 'redirect_users_by_role', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 248512,
"author": "David F. Carr",
"author_id": 108454,
"author_profile": "https://wordpress.stackexchange.com/users/108454",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to use a test like </p>\n\n<pre><code>if(current_user_can('edit_posts'))\n</code></pre>\n\n<p>rather than testing for a specific role name, so that you're basing it on capabilities that might be possessed or not by multiple roles. Depends on why you're trying to steer users away from the dashboard.</p>\n"
},
{
"answer_id": 248586,
"author": "Jordan W.",
"author_id": 72933,
"author_profile": "https://wordpress.stackexchange.com/users/72933",
"pm_score": 0,
"selected": false,
"text": "<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>\n\n<pre><code>function admin_login_redirect( $url, $request, $user ){\n //is there a user\n if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {\n //is user admin\n if( $user->has_cap( 'administrator' ) ) {\n //go do admin stuff\n $url = admin_url();\n //but wait there's more\n }\n }\n return $url;\n}\nadd_filter('login_redirect', 'admin_login_redirect', 10, 3 );\n\nfunction staff_login_redirect( $url, $request, $user ){\n if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {\n if( $user->has_cap('staff') && strpos($_REQUEST['redirect_to'], 'gf_entries') == false ) {\n //please god work\n $url = home_url() . '/resources';\n //but waittt there's more\n } else {\n //damnit all\n if( $user->has_cap('staff') && isset($_REQUEST['redirect_to']) && strpos($_REQUEST['redirect_to'], 'gf_entries') !== false) {\n\n $url = $_REQUEST['redirect_to'];\n\n }\n }\n }\n return $url;\n}\nadd_filter('login_redirect', 'staff_login_redirect', 10, 3 );\n\nfunction transient_login_redirect( $url, $request, $user ) {\n if ( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {\n if (!$user->has_cap('administrator') && !$user->has_cap('staff') ) {\n //go away\n $url= home_url('/access-denied');\n }\n }\n return $url;\n}\nadd_filter('login_redirect', 'transient_login_redirect', 10, 3);\n</code></pre>\n\n<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>\n\n<p>For admins, I just send them wherever. </p>\n\n<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>\n\n<p>Thanks for your help everyone!</p>\n"
}
] |
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": 357702,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 1,
"selected": false,
"text": "<p>You need to use fragment caching so enable PHP in the widget and then use the following tags:</p>\n\n<pre><code><!-- mfunc --> \n</code></pre>\n\n<p>The following links should help:</p>\n\n<p><a href=\"https://wordpress.org/support/topic/using-shortcodes-with-fragment-caching/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/using-shortcodes-with-fragment-caching/</a>\n<a href=\"https://www.justinsilver.com/technology/wordpress/w3-total-cache-fragment-caching-wordpress/\" rel=\"nofollow noreferrer\">https://www.justinsilver.com/technology/wordpress/w3-total-cache-fragment-caching-wordpress/</a></p>\n"
}
] |
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 this script to replace url from <code>example.com/wp</code> to <code>example.com</code> inside the database <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a> </p>\n\n<p>Follow these few steps.</p>\n\n<ol>\n<li>Move all your website files to root from <code>/wp</code> folder.</li>\n<li>Upload the script folder to your web root. </li>\n<li>Browse to the script file URL in your web browser. eg. <a href=\"http://example.com/Search-Replace-DB/\" rel=\"nofollow noreferrer\">http://example.com/Search-Replace-DB/</a></li>\n<li>Fill in the fields as needed.</li>\n<li>Hit on run button</li>\n</ol>\n\n<p>It will replace all your old string to your new string inside the database.</p>\n"
},
{
"answer_id": 248530,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Move Site No need to Delete</strong></p>\n\n<p>Step-1 : Login to Cpanel and move all folder to root folder (Normally public_html)</p>\n\n<p>Step-2 : Now,Show hidden file and rename htaccess file.</p>\n\n<p>Step-3 : Goto Database (i.e. phpmyadmin) and open wp_options table.Change site_url and home_url make it to (<a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a>)</p>\n\n<p>Step-4 : Login to admin panle go to Settings and update paramlinks.</p>\n\n<p>Step-5 :That's it.</p>\n\n<p><strong>Some Issue while Move site</strong></p>\n\n<ol>\n<li><p>Home Page not displayed : Go to appreance and active theme again.</p></li>\n<li><p>Admin is not open or white screen: Reupload all except wp-content folder</p></li>\n<li><p>404 Page Not Found : Remove htaccess and update paramlinks</p></li>\n<li><p>Site navigate to old url : change home_url and site_url</p></li>\n</ol>\n"
}
] |
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>. You can set a own function to render the comment list: <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_comments\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_list_comments</a>.</p>\n\n<p>After some googling, i found a great and complete article that may help you:\n<a href=\"https://blog.josemcastaneda.com/2013/05/29/custom-comment/\" rel=\"nofollow noreferrer\">https://blog.josemcastaneda.com/2013/05/29/custom-comment/</a></p>\n"
},
{
"answer_id": 248603,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<p>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! </p>\n\n<p>For theme functions.php or plug-in:</p>\n\n<pre><code>add_filter( 'get_comment_author', 'wpse_use_user_real_name', 10, 3 ) ;\n\n//use registered commenter first and/or last names if available\nfunction wpse_use_user_real_name( $author, $comment_id, $comment ) {\n\n $firstname = '' ;\n $lastname = '' ;\n\n //returns 0 for unregistered commenters\n $user_id = $comment->user_id ;\n\n if ( $user_id ) {\n\n $user_object = get_userdata( $user_id ) ;\n\n $firstname = $user_object->user_firstname ;\n\n $lastname = $user_object->user_lastname ; \n\n }\n\n if ( $firstname || $lastname ) {\n\n $author = $firstname . ' ' . $lastname ; \n\n //remove blank space if one of two names is missing\n $author = trim( $author ) ;\n\n }\n\n return $author ;\n\n}\n</code></pre>\n\n<p>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?). </p>\n\n<p>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.</p>\n"
},
{
"answer_id": 393150,
"author": "manolomunoz",
"author_id": 210066,
"author_profile": "https://wordpress.stackexchange.com/users/210066",
"pm_score": 1,
"selected": false,
"text": "<p>With the $comment object you can get the name and by means of conditionals you can show the author as you want.<br />\nHere I leave an example to show name and first letter of the surname (if any).</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'get_comment_author', 'mmr_use_user_real_name', 10, 3 );\nfunction mmr_use_user_real_name( $author, $comment_id, $comment ) {\n\n $firstname = '';\n $lastname = '';\n $author_name = $comment->comment_author;\n\n if ( $author_name ) {\n $nombre_partes = explode( ' ', $author_name );\n $firstname = $nombre_partes[0];\n $lastname = $nombre_partes[1];\n if ( $lastname ) {\n $custom_lastname = substr( $lastname, 0, 1 );\n $author = $firstname . ' ' . $custom_lastname . '.';\n } else {\n $author = $firstname;\n }\n }\n\n return $author;\n}\n</code></pre>\n"
}
] |
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>. You can set a own function to render the comment list: <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_comments\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_list_comments</a>.</p>\n\n<p>After some googling, i found a great and complete article that may help you:\n<a href=\"https://blog.josemcastaneda.com/2013/05/29/custom-comment/\" rel=\"nofollow noreferrer\">https://blog.josemcastaneda.com/2013/05/29/custom-comment/</a></p>\n"
},
{
"answer_id": 248603,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<p>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! </p>\n\n<p>For theme functions.php or plug-in:</p>\n\n<pre><code>add_filter( 'get_comment_author', 'wpse_use_user_real_name', 10, 3 ) ;\n\n//use registered commenter first and/or last names if available\nfunction wpse_use_user_real_name( $author, $comment_id, $comment ) {\n\n $firstname = '' ;\n $lastname = '' ;\n\n //returns 0 for unregistered commenters\n $user_id = $comment->user_id ;\n\n if ( $user_id ) {\n\n $user_object = get_userdata( $user_id ) ;\n\n $firstname = $user_object->user_firstname ;\n\n $lastname = $user_object->user_lastname ; \n\n }\n\n if ( $firstname || $lastname ) {\n\n $author = $firstname . ' ' . $lastname ; \n\n //remove blank space if one of two names is missing\n $author = trim( $author ) ;\n\n }\n\n return $author ;\n\n}\n</code></pre>\n\n<p>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?). </p>\n\n<p>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.</p>\n"
},
{
"answer_id": 393150,
"author": "manolomunoz",
"author_id": 210066,
"author_profile": "https://wordpress.stackexchange.com/users/210066",
"pm_score": 1,
"selected": false,
"text": "<p>With the $comment object you can get the name and by means of conditionals you can show the author as you want.<br />\nHere I leave an example to show name and first letter of the surname (if any).</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'get_comment_author', 'mmr_use_user_real_name', 10, 3 );\nfunction mmr_use_user_real_name( $author, $comment_id, $comment ) {\n\n $firstname = '';\n $lastname = '';\n $author_name = $comment->comment_author;\n\n if ( $author_name ) {\n $nombre_partes = explode( ' ', $author_name );\n $firstname = $nombre_partes[0];\n $lastname = $nombre_partes[1];\n if ( $lastname ) {\n $custom_lastname = substr( $lastname, 0, 1 );\n $author = $firstname . ' ' . $custom_lastname . '.';\n } else {\n $author = $firstname;\n }\n }\n\n return $author;\n}\n</code></pre>\n"
}
] |
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_post_link(); ?></code> with the following code:</p>\n\n<p>For previous post:</p>\n\n<pre><code> <?php\n $prev_post = get_previous_post();\n $prev_user = get_user_by( 'id', $prev_post->post_author );\n if (!empty( $prev_post )): ?>\n <a href=\"<?php echo $prev_post->guid ?>\"><?php echo $prev_post->post_title ?> (<?php echo $prev_user->first_name . ' ' . $prev_user->last_name; ?>)</a>\n <?php endif ?>\n</code></pre>\n\n<p>For next post:</p>\n\n<pre><code> <?php\n $next_post = get_next_post();\n $next_user = get_user_by( 'id', $next_post->post_author );\n if (!empty( $prev_post )): ?>\n <a href=\"<?php echo $next_post->guid ?>\"><?php echo $next_post->post_title ?> (<?php echo $next_user->first_name . ' ' . $next_user->last_name; ?>)</a>\n <?php endif ?>\n</code></pre>\n\n<p>You also can control from which categories WordPress should select previous and next posts. <code>get_previous_post</code> and <code>get_next_post</code> accept two parameters:</p>\n\n<ul>\n<li><code>(bool) $in_same_cat</code> — prev/next posts will be selected from the same category as you current post </li>\n<li><code>(string) $excluded_categories</code> — posts related to these categories will be skipped</li>\n</ul>\n\n<p>More details about these parameters you may <a href=\"https://codex.wordpress.org/Function_Reference/get_previous_post\" rel=\"nofollow noreferrer\">find here</a></p>\n"
},
{
"answer_id": 248622,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": 1,
"selected": false,
"text": "<p>You can create a custom function. For this you need to use </p>\n\n<pre><code>// Add in single.php where you want to show next icon.\n$nextPost = get_next_post(); // Get the next post detail\n$nextPostID = $nextPost->ID; // Get the post id of next post and pass it \necho get_post_link_with_post_author_name( $nextPostID );\n</code></pre>\n\n<p>And define the <code>get_post_link_with_post_author_name()</code> in your active theme's functions.php as : </p>\n\n<pre><code>// This function returns postname, post author and link to it.\nfunction get_post_link_with_post_author_name( $postID ){\n // you have got the postID , now you need to fetch the post name, post url and post author\n $post = get_post( $postID ); \n $post_title = $post->post_title;\n $post_author_id = $post->post_author;\n $author_detail = get_user_by( 'ID', $post_author_id );\n $post_author_name = $author_detail->display_name;\n $post_url = get_permalink( $postID );\n $respone = \"<a href='$post_url'>$post_title >> By $post_author_name</a>\";\n return $response;\n}\n</code></pre>\n\n<p>You can use the same function for previous post link with post name and author name. You just need to get the previous post id using <code>get_previous_post()</code> and pass that post id to the above function.</p>\n"
}
] |
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=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow noreferrer\"><code>get_post_type()</code></a><br />\nWhich calls <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow noreferrer\"><code>get_post()</code></a> which if we're <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L519\" rel=\"nofollow noreferrer\">not passing some sort of Object</a><br />\nCalls <a href=\"https://developer.wordpress.org/reference/classes/wp_post/get_instance/\" rel=\"nofollow noreferrer\"><code>WP_Post::get_instance()</code></a> which does a conditional check to ensure whatever passed<br /> <a href=\"http://php.net/manual/en/function.is-numeric.php\" rel=\"nofollow noreferrer\"><code>is_numeric()</code></a> which will return true for string \"numbers\".<br />\nFinally, it <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-post.php#L217\" rel=\"nofollow noreferrer\">converts the passed number to an integer</a> and returns it up the stack.</p>\n\n<p>All of the above has shipped with WordPress 4.7 so whatever the issue is may be deeper than the built-in <code>get_post_type()</code> since it will accept both integers and \"string integers\".</p>\n"
},
{
"answer_id": 248650,
"author": "Stephen",
"author_id": 11023,
"author_profile": "https://wordpress.stackexchange.com/users/11023",
"pm_score": 3,
"selected": true,
"text": "<p>According to the devs at WP (<a href=\"https://core.trac.wordpress.org/ticket/39164\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/39164</a>):</p>\n\n<p>\"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.\nget_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.\"</p>\n\n<p>So I would consider this the definitive answer. The behavior has changed to something better, it was just a surprise that it worked before.</p>\n"
}
] |
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=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow noreferrer\"><code>get_post_type()</code></a><br />\nWhich calls <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow noreferrer\"><code>get_post()</code></a> which if we're <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L519\" rel=\"nofollow noreferrer\">not passing some sort of Object</a><br />\nCalls <a href=\"https://developer.wordpress.org/reference/classes/wp_post/get_instance/\" rel=\"nofollow noreferrer\"><code>WP_Post::get_instance()</code></a> which does a conditional check to ensure whatever passed<br /> <a href=\"http://php.net/manual/en/function.is-numeric.php\" rel=\"nofollow noreferrer\"><code>is_numeric()</code></a> which will return true for string \"numbers\".<br />\nFinally, it <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-post.php#L217\" rel=\"nofollow noreferrer\">converts the passed number to an integer</a> and returns it up the stack.</p>\n\n<p>All of the above has shipped with WordPress 4.7 so whatever the issue is may be deeper than the built-in <code>get_post_type()</code> since it will accept both integers and \"string integers\".</p>\n"
},
{
"answer_id": 248650,
"author": "Stephen",
"author_id": 11023,
"author_profile": "https://wordpress.stackexchange.com/users/11023",
"pm_score": 3,
"selected": true,
"text": "<p>According to the devs at WP (<a href=\"https://core.trac.wordpress.org/ticket/39164\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/39164</a>):</p>\n\n<p>\"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.\nget_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.\"</p>\n\n<p>So I would consider this the definitive answer. The behavior has changed to something better, it was just a surprise that it worked before.</p>\n"
}
] |
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 jQuery object so you can use it. </p>\n\n<p>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.</p>\n\n<pre><code>(function($){\nvar array = [];\nvar array1 = $('#input_8_3').val().split(',');\n$(\"#input_8_3\").val(array.join());\n\n$('div.thumbn').click(function() {\n var text = $(this).attr(\"id\").replace('img-act-','');\n var oldtext = $('#input_8_3').val();\n if ($(this).hasClass('chosen-img'))\n {\n\n $('#input_8_3').val(text+oldtext); \n var index = array.indexOf(text);\n if (index !== -1)\n {\n array.splice(index, 1);\n }\n\n array1.push(text);\n $(this).removeClass('chosen-img');\n }\n else\n {\n array.push(text);\n var index = array1.indexOf(text);\n if (index !== -1)\n {\n array1.splice(index, 1);\n }\n $(this).addClass('chosen-img');\n }\n $(\"#input_8_3\").val(array.join());\n $(\"#input_8_4\").val(array1.join());\n console.log(array1);\n});\n})(jQuery);\n</code></pre>\n"
},
{
"answer_id": 248716,
"author": "mr__culpepper",
"author_id": 108606,
"author_profile": "https://wordpress.stackexchange.com/users/108606",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Uncaught TypeError: $ is not a function(…)\n</code></pre>\n\n<p>This is due to WordPress's interaction with jQuery.</p>\n\n<p>A work-around is replacing instances of '$' with 'jQuery'</p>\n"
},
{
"answer_id": 248762,
"author": "Schon Garcia",
"author_id": 108628,
"author_profile": "https://wordpress.stackexchange.com/users/108628",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I use in my scripts file for jQuery functions. It should work in your case to.</p>\n\n<pre><code> $(document).ready(function ($) { ... })\n</code></pre>\n"
}
] |
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 jQuery object so you can use it. </p>\n\n<p>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.</p>\n\n<pre><code>(function($){\nvar array = [];\nvar array1 = $('#input_8_3').val().split(',');\n$(\"#input_8_3\").val(array.join());\n\n$('div.thumbn').click(function() {\n var text = $(this).attr(\"id\").replace('img-act-','');\n var oldtext = $('#input_8_3').val();\n if ($(this).hasClass('chosen-img'))\n {\n\n $('#input_8_3').val(text+oldtext); \n var index = array.indexOf(text);\n if (index !== -1)\n {\n array.splice(index, 1);\n }\n\n array1.push(text);\n $(this).removeClass('chosen-img');\n }\n else\n {\n array.push(text);\n var index = array1.indexOf(text);\n if (index !== -1)\n {\n array1.splice(index, 1);\n }\n $(this).addClass('chosen-img');\n }\n $(\"#input_8_3\").val(array.join());\n $(\"#input_8_4\").val(array1.join());\n console.log(array1);\n});\n})(jQuery);\n</code></pre>\n"
},
{
"answer_id": 248716,
"author": "mr__culpepper",
"author_id": 108606,
"author_profile": "https://wordpress.stackexchange.com/users/108606",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Uncaught TypeError: $ is not a function(…)\n</code></pre>\n\n<p>This is due to WordPress's interaction with jQuery.</p>\n\n<p>A work-around is replacing instances of '$' with 'jQuery'</p>\n"
},
{
"answer_id": 248762,
"author": "Schon Garcia",
"author_id": 108628,
"author_profile": "https://wordpress.stackexchange.com/users/108628",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I use in my scripts file for jQuery functions. It should work in your case to.</p>\n\n<pre><code> $(document).ready(function ($) { ... })\n</code></pre>\n"
}
] |
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 WP installation to be checked and be placed in a \"privileged\" context for all the code to run.</p>\n\n<p>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).</p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 248739,
"author": "Daniel Mulder",
"author_id": 86859,
"author_profile": "https://wordpress.stackexchange.com/users/86859",
"pm_score": 0,
"selected": false,
"text": "<p>Yes they can. Its simple. If a user is logged in then within the same browser session the ajax then you can just ask the wp api if the user is logged in from anywhere when used with the nopriv or public api interface of wordpress like so <a href=\"https://gist.github.com/fazlurr/9f9c7cac603e026bd03b\" rel=\"nofollow noreferrer\">https://gist.github.com/fazlurr/9f9c7cac603e026bd03b</a></p>\n"
},
{
"answer_id": 248740,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<h2>If I recall well</h2>\n<p><a href=\"http://v2.wp-api.org/guide/authentication/\" rel=\"nofollow noreferrer\">From</a></p>\n<blockquote>\n<p>There are several options for authenticating with the API. The basic choice boils down to:</p>\n<p>Are you a plugin/theme running on the site? Use cookie authentication\nAre you a desktop/web/mobile client accessing the site externally? Use OAuth authentication, application passwords, or basic authentication.</p>\n</blockquote>\n<p>The only problem with oAuth is you need to use 1.0 standard. oAuth 2.0 is easier to implement, but the decision was we are not ready since most of the websites don't use HTTP/2</p>\n"
}
] |
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 WP installation to be checked and be placed in a \"privileged\" context for all the code to run.</p>\n\n<p>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).</p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 248739,
"author": "Daniel Mulder",
"author_id": 86859,
"author_profile": "https://wordpress.stackexchange.com/users/86859",
"pm_score": 0,
"selected": false,
"text": "<p>Yes they can. Its simple. If a user is logged in then within the same browser session the ajax then you can just ask the wp api if the user is logged in from anywhere when used with the nopriv or public api interface of wordpress like so <a href=\"https://gist.github.com/fazlurr/9f9c7cac603e026bd03b\" rel=\"nofollow noreferrer\">https://gist.github.com/fazlurr/9f9c7cac603e026bd03b</a></p>\n"
},
{
"answer_id": 248740,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<h2>If I recall well</h2>\n<p><a href=\"http://v2.wp-api.org/guide/authentication/\" rel=\"nofollow noreferrer\">From</a></p>\n<blockquote>\n<p>There are several options for authenticating with the API. The basic choice boils down to:</p>\n<p>Are you a plugin/theme running on the site? Use cookie authentication\nAre you a desktop/web/mobile client accessing the site externally? Use OAuth authentication, application passwords, or basic authentication.</p>\n</blockquote>\n<p>The only problem with oAuth is you need to use 1.0 standard. oAuth 2.0 is easier to implement, but the decision was we are not ready since most of the websites don't use HTTP/2</p>\n"
}
] |
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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.