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
|
---|---|---|---|---|---|---|
192,429 |
<p>I was writing a small plugin to remove some menu items for non-admin users from the backend, and discovered that my plugin didn't do anything unless I specified a priority in my code:</p>
<pre><code>add_action('admin_bar_menu', 'remove_toolbar_items', 999);
</code></pre>
<p>Without the <code>999</code>, the code doesn't remove the items in my <code>remove_toolbar_items</code> function, and with it it works great:</p>
<pre><code>function remove_toolbar_items( $wp_admin_bar ) {
if ( !current_user_can( 'manage_options' ) ) {
$wp_admin_bar->remove_node('new-post');
$wp_admin_bar->remove_node('comments');
}
}
</code></pre>
<p>The <a href="https://developer.wordpress.org/reference/functions/add_action/" rel="noreferrer">docs</a> for the priority parameter state:</p>
<blockquote>
<p>Used to specify the order in which the functions associated with a
particular action are executed. Lower numbers correspond with earlier
execution, and functions with the same priority are executed in the
order in which they were added to the action. Default value: 10</p>
</blockquote>
<p>However I didn't find anything that explains how you're supposed to determine what priority to use. How do you determine when to use priority, and what priority to use? I feel like I could've been scratching my head for hours if I hadn't toyed around with the priority parameter.</p>
<p>Also, I see that the default priority is 10, but is there a known range of priority values?</p>
|
[
{
"answer_id": 192431,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>range of priority values?\n range of priority values?</p>\n</blockquote>\n\n<p>Generally, speaking, you can't know <em>a priori</em> what priority something is hooked with. The priority needed depends on how other callbacks where hooked in. Often that is the default value of 10 but it could be anywhere between <code>PHP_INT_MIN</code> (negative integers are still integers) and <code>PHP_INT_MAX</code> and there is no way to be sure except by experiment and, if possible (as with the Core and any themes or plugins that you are specifically concerned with), by examining the source. </p>\n"
},
{
"answer_id": 192432,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress puts your actions into an array with an indexed priorities. You can see this by printing out ( in the admin panel <code>admin_init</code> ) <code>$wp_filter</code>:</p>\n\n<p><em>*<strong>Note</strong>*</em> as @s_ha_dum points out in the comments below, <code>admin_init</code> may not catch <em>all</em> added hooks into the action, the more reliable print out may be hooking into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/shutdown\" rel=\"noreferrer\"><code>shutdown</code></a> instead.</p>\n\n<pre><code>function filter_print() {\n global $wp_filter;\n print_r( $wp_filter['admin_bar_menu'] );\n die();\n}\nadd_action( 'admin_init', 'filter_print' );\n</code></pre>\n\n<p>This gives us a neat array that looks something like this: ( simplified )</p>\n\n<pre><code>Array(\n [admin_bar_menu] => Array (\n [0] => Array (\n [wp_admin_bar_my_account_menu] => Array (\n [function] => wp_admin_bar_my_account_menu\n [accepted_args] => 1\n )\n [wp_admin_bar_sidebar_toggle] => Array (\n [function] => wp_admin_bar_sidebar_toggle\n [accepted_args] => 1\n )\n )\n\n [4] => Array (\n [wp_admin_bar_search_menu] => Array (\n [function] => wp_admin_bar_search_menu\n [accepted_args] => 1\n )\n )\n\n [7] => Array (\n [wp_admin_bar_my_account_item] => Array (\n [function] => wp_admin_bar_my_account_item\n [accepted_args] => 1\n )\n )\n\n [10] => Array (\n [wp_admin_bar_wp_menu] => Array (\n [function] => wp_admin_bar_wp_menu\n [accepted_args] => 1\n )\n )\n\n [20] => ...\n )\n)\n</code></pre>\n\n<p>The 0, 4, 7, 10, and so forth are the priorities of the actions, when a new action is added it's defaulted to 10, similar to index 0 in the example above, they are just stacked into the same index of the array. Considering that many hooks are added into this particular action you would want to at the very end or at last after a specific action was run ( such as menus ). 1 of the two priorities could also work just as effectively: <code>81</code> or <code>201</code>. </p>\n\n<p>For the most part, the default priority of 10 is sufficient enough. Other times you want to add your hook direct after another ( to maybe nullify it's purpose or remove a specific item ) at which case you can use the <code>global $wp_filter;</code> to figure out where it needs to go. </p>\n"
},
{
"answer_id": 289490,
"author": "Mohammed Asif",
"author_id": 133844,
"author_profile": "https://wordpress.stackexchange.com/users/133844",
"pm_score": 3,
"selected": false,
"text": "<p>Well, there's a way to find the priority of an action.</p>\n\n<p>we can use the following code<code>has_action( $tag, $function_to_check )</code> which Optionally returns the priority on that hook for the specified function.</p>\n\n<p>Ref: <a href=\"https://codex.wordpress.org/Function_Reference/has_action\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/has_action</a></p>\n"
},
{
"answer_id": 349773,
"author": "harrrrrrry",
"author_id": 73977,
"author_profile": "https://wordpress.stackexchange.com/users/73977",
"pm_score": -1,
"selected": false,
"text": "<p>Just in case someone is looking for WordPress Action Priority/Reference list, the full hook link is here: </p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/</a></p>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26666/"
] |
I was writing a small plugin to remove some menu items for non-admin users from the backend, and discovered that my plugin didn't do anything unless I specified a priority in my code:
```
add_action('admin_bar_menu', 'remove_toolbar_items', 999);
```
Without the `999`, the code doesn't remove the items in my `remove_toolbar_items` function, and with it it works great:
```
function remove_toolbar_items( $wp_admin_bar ) {
if ( !current_user_can( 'manage_options' ) ) {
$wp_admin_bar->remove_node('new-post');
$wp_admin_bar->remove_node('comments');
}
}
```
The [docs](https://developer.wordpress.org/reference/functions/add_action/) for the priority parameter state:
>
> Used to specify the order in which the functions associated with a
> particular action are executed. Lower numbers correspond with earlier
> execution, and functions with the same priority are executed in the
> order in which they were added to the action. Default value: 10
>
>
>
However I didn't find anything that explains how you're supposed to determine what priority to use. How do you determine when to use priority, and what priority to use? I feel like I could've been scratching my head for hours if I hadn't toyed around with the priority parameter.
Also, I see that the default priority is 10, but is there a known range of priority values?
|
>
> range of priority values?
> range of priority values?
>
>
>
Generally, speaking, you can't know *a priori* what priority something is hooked with. The priority needed depends on how other callbacks where hooked in. Often that is the default value of 10 but it could be anywhere between `PHP_INT_MIN` (negative integers are still integers) and `PHP_INT_MAX` and there is no way to be sure except by experiment and, if possible (as with the Core and any themes or plugins that you are specifically concerned with), by examining the source.
|
192,434 |
<p>I'm using CPT UI and I've manage to create a working custom post type called "Cars"<br/>
I would like to have "Sub Custom Post Type" like "Honda" for example and models like "M1", "M2", "M3" related to "Honda".<br/>
<br/>
So if I click on Honda it will display the models.<br/>
How can I achieve the same concept of POST+CATEGORY+SUBCATEOGRY for custom post type <br/> (i.e Cars+Honda+M1)</p>
|
[
{
"answer_id": 192436,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress doesn't support nested post types, though you can created hierarchical types similar to the Core \"Page\" type. However, what you are describing, including this sample \"POST+CATEGORY+SUBCATEOGRY\" is a <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow\">custom taxonomy</a> for your Car post type. The Codex has examples, but you would need something like this (roughly, I am sure this needs tweaked): </p>\n\n<pre><code>add_action( 'init', 'create_book_tax' );\n\nfunction create_book_tax() {\n register_taxonomy(\n 'make',\n 'cars',\n array(\n 'label' => __( 'Make' ),\n 'rewrite' => array( 'slug' => 'make' ),\n 'hierarchical' => true,\n )\n );\n}\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy#Example\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/register_taxonomy#Example</a></p>\n"
},
{
"answer_id": 192466,
"author": "Anam Shah",
"author_id": 75030,
"author_profile": "https://wordpress.stackexchange.com/users/75030",
"pm_score": 0,
"selected": false,
"text": "<p>yeah as answered by <strong>@s_ha_dum</strong> wordpress doesn't support the nested post type you can achieve it by xreating the custom taxonomy and by using parent child relation you can acheive your scenario. I am explaning the code as below.</p>\n\n<p>It might be helpful to you.</p>\n\n<pre><code> add_action( 'init', 'create_post_type' );\n function create_post_type() {\nregister_taxonomy('car', 'cars', array(\n 'hierarchical' => true,\n 'labels' => array(\n 'name' => _x( 'Car Category', 'taxonomy general name' ),\n 'singular_name' => _x( 'Car -Category', 'Car Category' ),\n 'search_items' => __( 'Search Car Categories' ),\n 'all_items' => __( 'All Car Categories' ),\n 'parent_item' => __( 'Parent Car Category' ),\n 'parent_item_colon' => __( 'Parent Car Category:' ),\n 'edit_item' => __( 'Edit Car Category' ),\n 'update_item' => __( 'Update Car Category' ),\n 'add_new_item' => __( 'Add New Car Category' ),\n 'new_item_name' => __( 'New Car Category Name' ),\n 'menu_name' => __( 'Car Categories' ),\n ),\n\n 'rewrite' => array(\n 'slug' => 'car', \n 'with_front' => false, \n 'hierarchical' => true \n ),\n ));\n\n register_post_type( 'cars',\n array(\n 'labels' => array(\n 'name' => __( 'Cars' ),\n 'singular_name' => __( 'Cars' ),\n 'menu_name' => __( 'Cars' ),\n 'name_admin_bar' => __( 'Cars' ),\n 'all_items' => __( 'Group of Companies' ),\n 'add_new' => __( 'Add New Car' ),\n 'new_item' => __( 'Add New Car' ),\n 'add_new_item' => __( 'Add New Car' ),\n 'edit_item' => __( 'Edit Car' ),\n 'view_item' => __( 'View Car' ),\n ),\n 'public' => true,\n 'has_archive' => true,\n 'supports' => array(\"title\", \"editor\", \"thumbnail\")\n )\n );\n</code></pre>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192434",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74315/"
] |
I'm using CPT UI and I've manage to create a working custom post type called "Cars"
I would like to have "Sub Custom Post Type" like "Honda" for example and models like "M1", "M2", "M3" related to "Honda".
So if I click on Honda it will display the models.
How can I achieve the same concept of POST+CATEGORY+SUBCATEOGRY for custom post type
(i.e Cars+Honda+M1)
|
WordPress doesn't support nested post types, though you can created hierarchical types similar to the Core "Page" type. However, what you are describing, including this sample "POST+CATEGORY+SUBCATEOGRY" is a [custom taxonomy](https://codex.wordpress.org/Function_Reference/register_taxonomy) for your Car post type. The Codex has examples, but you would need something like this (roughly, I am sure this needs tweaked):
```
add_action( 'init', 'create_book_tax' );
function create_book_tax() {
register_taxonomy(
'make',
'cars',
array(
'label' => __( 'Make' ),
'rewrite' => array( 'slug' => 'make' ),
'hierarchical' => true,
)
);
}
```
<https://codex.wordpress.org/Function_Reference/register_taxonomy#Example>
|
192,450 |
<p>I am using multisite to translate WordPress website and I have the plugin <a href="https://wordpress.org/plugins/nmedia-user-file-uploader/" rel="nofollow noreferrer">https://wordpress.org/plugins/nmedia-user-file-uploader/</a>
which I want to be accessible from all languages. From all site you should see the same uploaded content and settings.
How can I achieve that?
Currently if I upload in one language I won't be able to see in another.</p>
|
[
{
"answer_id": 192494,
"author": "JJ Rohrer",
"author_id": 8972,
"author_profile": "https://wordpress.stackexchange.com/users/8972",
"pm_score": -1,
"selected": false,
"text": "<p>I almost thought this was a duplicate to <a href=\"https://wordpress.stackexchange.com/questions/15939/network-wide-plugin-settings-management\">Network-Wide Plugin Settings Management</a> , but I see you also want shared content.</p>\n\n<p>Basically, this is tough and situation and plugin dependent. I'm a fan of WPMUDev's premium New Blog Template for copying content and settings upon blog creation, but it doesn't help with subsequent settings and content changes.</p>\n\n<p>WPMUDev also has <a href=\"https://premium.wpmudev.org/project/multisite-content-copier/\" rel=\"nofollow noreferrer\">MultiSite Content Copier</a> which might work for you. I haven't tried it myself, but it looks reasonable. There may very well be other, and cheaper, options, too.</p>\n\n<p>I hope this helps - good luck.</p>\n"
},
{
"answer_id": 304792,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The generic way to do it, is by using the <code>pre_option_{option}</code> <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/pre_option_(option_name)\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/pre_option_(option_name)</a> filter to override the \"local\" settings and use the value being stored in your \"main\" sub site.</p>\n\n<p>something like</p>\n\n<pre><code>add_filter( 'pre_option_the_plugin_option_name', function () {\n // Code assumes that \"blog\" 1 is the main one in which the relevant settings are stored.\n if (get_current_blog_id() != 1) {\n return get_blog_option(1, 'the_plugin_option_name');\n }\n\n return false;\n}\n</code></pre>\n\n<p>Depending on the complexity of the plugin, it might not be enough and you will need additional overrides, but this type of code should be enough for simple cases.</p>\n"
}
] |
2015/06/23
|
[
"https://wordpress.stackexchange.com/questions/192450",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75137/"
] |
I am using multisite to translate WordPress website and I have the plugin <https://wordpress.org/plugins/nmedia-user-file-uploader/>
which I want to be accessible from all languages. From all site you should see the same uploaded content and settings.
How can I achieve that?
Currently if I upload in one language I won't be able to see in another.
|
The generic way to do it, is by using the `pre_option_{option}` <https://codex.wordpress.org/Plugin_API/Filter_Reference/pre_option_(option_name)> filter to override the "local" settings and use the value being stored in your "main" sub site.
something like
```
add_filter( 'pre_option_the_plugin_option_name', function () {
// Code assumes that "blog" 1 is the main one in which the relevant settings are stored.
if (get_current_blog_id() != 1) {
return get_blog_option(1, 'the_plugin_option_name');
}
return false;
}
```
Depending on the complexity of the plugin, it might not be enough and you will need additional overrides, but this type of code should be enough for simple cases.
|
192,478 |
<p>Its simple and answered quite often: I want to get the post thumbnail variable. Even if there is a lot of input, I could not make it work for me.</p>
<p>Here is my current code I use somewhere inside my <code>front_page.php</code> template:</p>
<pre><code><?php
$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<div class="post">';
echo '<div class="post_thumb" style="background-image:url('.get_the_post_thumbnail( $recent['ID'], 'thumbnail').')"></div>';
echo '<div class="content"';
echo '<h2 class="post_title">';
echo '<a href="'.get_permalink($recent["ID"]).'" title="'.$recent["post_title"].'" >'.$recent["post_title"].'</a>';
echo '</h2>';
echo '<p class="post_excerpt">'.$recent["post_excerpt"].'</p>';
echo '</div>'; //content
echo '</div>'; //.post
}
?>
</code></pre>
<p>This works quite good, except for the <code>get_the_post_thumbnail()</code> part.</p>
<p>I know, that I can get the thumbnail url using</p>
<pre><code>$post_thumbnail_id = get_post_thumbnail_id($post->ID);
$post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id );
</code></pre>
<p>But I am not able to implement this code inside of my own. I tried to add it inside <code>foreach</code> and although before, but both does not seem to work. I do not receive any errors I could look for, it only outputs "nothing", meaning there is no <code>style="background-image: url()";</code>.</p>
<p>I would love if there is someone that could not only show, but explain, why my code is not working. I guess, that if I have solved this problem, my next question would be *where do I have to add <code>'thumbnail'</code> in order to output the correct image size?</p>
<p><strong>Broken code</strong></p>
<pre><code><?php
$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$post_thumbnail_id = get_post_thumbnail_id($post->ID);
$post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id );
echo '<div class="post">';
echo '<div class="post_thumb" style="background-image:url('.$post_thumbnail_url.')"></div>';
echo '<div class="content"';
echo '<h2 class="post_title">';
echo '<a href="'.get_permalink($recent["ID"]).'" title="'.$recent["post_title"].'" >'.$recent["post_title"].'</a>';
echo '</h2>';
echo '<p class="post_excerpt">'.$recent["post_excerpt"].'</p>';
echo '</div>'; //content
echo '</div>'; //.post
}
?>
</code></pre>
|
[
{
"answer_id": 192480,
"author": "Nia Skywalk",
"author_id": 74433,
"author_profile": "https://wordpress.stackexchange.com/users/74433",
"pm_score": 2,
"selected": true,
"text": "<p>Initially, I saw the double and single quotes all jumbled up. This did fix some of what I saw, but I finally had time to test the code you put up.</p>\n\n<p>First step, I used <code>var_dump</code> on <code>$recent_posts</code> to make sure I was getting the usable values.</p>\n\n<p>Next, I echoed each variable as it was called, to make sure I knew what was being generated. I discovered that this line, as @james-barrett said, was not calling correct information:</p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($post->ID);\n</code></pre>\n\n<p>So, I used @james-barrett's suggestion and changed it to: </p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($recent[\"ID\"]);\n</code></pre>\n\n<p>Which then worked to get the correct ID.</p>\n\n<p>After I was calling the correct information, the <code>url()</code> portion was filling correctly, but the next problem was getting the correct size called.</p>\n\n<p>I did some research and discovered how the files were saved in the 'uploads' folder and then continued on to search for a way to access a function that would allow me to reach the one labled \"thumbnail\". The solution I found might not work with other sizes, or perhaps you could do more research after this, but I changed the <code>$post_thumbnail_url</code> variable to this:</p>\n\n<pre><code>$post_thumbnail_url = wp_get_attachment_thumb_url( $post_thumbnail_id );\n</code></pre>\n\n<p>Which resulted in the 150x150 image being called.</p>\n\n<p>After all was said and done, I converted your <strong>broken code</strong> above to this working code:</p>\n\n<pre><code><?php \n$args = array( 'numberposts' => '2' );\n$recent_posts = wp_get_recent_posts( $args );\nforeach( $recent_posts as $recent ){\n $post_thumbnail_id = get_post_thumbnail_id($recent[\"ID\"]);\n $post_thumbnail_url = wp_get_attachment_thumb_url( $post_thumbnail_id );\n echo '<div class=\"post\">';\n echo '<div class=\"post_thumb\" style=\"background-image:url(\\''.$post_thumbnail_url.'\\')\"></div>';\n echo '<div class=\"content\"';\n echo '<h2 class=\"post_title\">';\n echo '<a href=\"'.get_permalink($recent[\"ID\"]).'\" title=\"'.$recent[\"post_title\"].'\" >'.$recent[\"post_title\"].'</a>';\n echo '</h2>';\n echo '<p class=\"post_excerpt\">'.$recent[\"post_excerpt\"].'</p>';\n echo '</div>'; //content\n echo '</div>'; //.post\n }\n?>\n</code></pre>\n\n<p>Note: I adjusted the url() to be url('') because some of my older browsers require the single quotes, but I suspect you can remove them.</p>\n"
},
{
"answer_id": 192498,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 0,
"selected": false,
"text": "<p>I think the issue is with the following line of code:</p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($post->ID);\n</code></pre>\n\n<p>It should be the ID of your <code>$recent</code> variable not <code>$post</code>.</p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($recent->ID);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($recent['ID']);\n</code></pre>\n\n<p>and to get a specific size of thumbnail you could do something like this:</p>\n\n<pre><code><?php\n foreach( $recent_posts as $recent ){\n $post_thumbnail_id = get_post_thumbnail_id($recent['ID']);\n $post_thumbnail_url = wp_get_attachment_image_src($post_thumbnail_id, 'thumbnail' );\n\n echo '<div class=\"post\">';\n echo '<div class=\"post_thumb\" style=\"background-image:url('.$post_thumbnail_url.')\"></div>';\n echo '<div class=\"content\"';\n echo '<h2 class=\"post_title\">';\n echo '<a href=\"'.get_permalink($recent[\"ID\"]).'\" title=\"'.$recent[\"post_title\"].'\" >'.$recent[\"post_title\"].'</a>';\n echo '</h2>';\n echo '<p class=\"post_excerpt\">'.$recent[\"post_excerpt\"].'</p>';\n echo '</div>'; //content\n echo '</div>'; //.post\n\n }\n?>\n</code></pre>\n"
}
] |
2015/06/24
|
[
"https://wordpress.stackexchange.com/questions/192478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75154/"
] |
Its simple and answered quite often: I want to get the post thumbnail variable. Even if there is a lot of input, I could not make it work for me.
Here is my current code I use somewhere inside my `front_page.php` template:
```
<?php
$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<div class="post">';
echo '<div class="post_thumb" style="background-image:url('.get_the_post_thumbnail( $recent['ID'], 'thumbnail').')"></div>';
echo '<div class="content"';
echo '<h2 class="post_title">';
echo '<a href="'.get_permalink($recent["ID"]).'" title="'.$recent["post_title"].'" >'.$recent["post_title"].'</a>';
echo '</h2>';
echo '<p class="post_excerpt">'.$recent["post_excerpt"].'</p>';
echo '</div>'; //content
echo '</div>'; //.post
}
?>
```
This works quite good, except for the `get_the_post_thumbnail()` part.
I know, that I can get the thumbnail url using
```
$post_thumbnail_id = get_post_thumbnail_id($post->ID);
$post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id );
```
But I am not able to implement this code inside of my own. I tried to add it inside `foreach` and although before, but both does not seem to work. I do not receive any errors I could look for, it only outputs "nothing", meaning there is no `style="background-image: url()";`.
I would love if there is someone that could not only show, but explain, why my code is not working. I guess, that if I have solved this problem, my next question would be \*where do I have to add `'thumbnail'` in order to output the correct image size?
**Broken code**
```
<?php
$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$post_thumbnail_id = get_post_thumbnail_id($post->ID);
$post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id );
echo '<div class="post">';
echo '<div class="post_thumb" style="background-image:url('.$post_thumbnail_url.')"></div>';
echo '<div class="content"';
echo '<h2 class="post_title">';
echo '<a href="'.get_permalink($recent["ID"]).'" title="'.$recent["post_title"].'" >'.$recent["post_title"].'</a>';
echo '</h2>';
echo '<p class="post_excerpt">'.$recent["post_excerpt"].'</p>';
echo '</div>'; //content
echo '</div>'; //.post
}
?>
```
|
Initially, I saw the double and single quotes all jumbled up. This did fix some of what I saw, but I finally had time to test the code you put up.
First step, I used `var_dump` on `$recent_posts` to make sure I was getting the usable values.
Next, I echoed each variable as it was called, to make sure I knew what was being generated. I discovered that this line, as @james-barrett said, was not calling correct information:
```
$post_thumbnail_id = get_post_thumbnail_id($post->ID);
```
So, I used @james-barrett's suggestion and changed it to:
```
$post_thumbnail_id = get_post_thumbnail_id($recent["ID"]);
```
Which then worked to get the correct ID.
After I was calling the correct information, the `url()` portion was filling correctly, but the next problem was getting the correct size called.
I did some research and discovered how the files were saved in the 'uploads' folder and then continued on to search for a way to access a function that would allow me to reach the one labled "thumbnail". The solution I found might not work with other sizes, or perhaps you could do more research after this, but I changed the `$post_thumbnail_url` variable to this:
```
$post_thumbnail_url = wp_get_attachment_thumb_url( $post_thumbnail_id );
```
Which resulted in the 150x150 image being called.
After all was said and done, I converted your **broken code** above to this working code:
```
<?php
$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$post_thumbnail_id = get_post_thumbnail_id($recent["ID"]);
$post_thumbnail_url = wp_get_attachment_thumb_url( $post_thumbnail_id );
echo '<div class="post">';
echo '<div class="post_thumb" style="background-image:url(\''.$post_thumbnail_url.'\')"></div>';
echo '<div class="content"';
echo '<h2 class="post_title">';
echo '<a href="'.get_permalink($recent["ID"]).'" title="'.$recent["post_title"].'" >'.$recent["post_title"].'</a>';
echo '</h2>';
echo '<p class="post_excerpt">'.$recent["post_excerpt"].'</p>';
echo '</div>'; //content
echo '</div>'; //.post
}
?>
```
Note: I adjusted the url() to be url('') because some of my older browsers require the single quotes, but I suspect you can remove them.
|
192,488 |
<p>I am building a site client who makes anywhere from 20-50 news posts per day. I'd like to have a news feed where it shows the date / post count as an H3 and then list all the posts for that day underneath.</p>
<p>Example...</p>
<p><strong>TODAY (4 posts)</strong>
- News Article Link
- News Article Link
- News Article Link
- News Article Link</p>
<p><strong>YESTERDAY (6 posts)</strong>
- News Article Link
- News Article Link
- News Article Link
- News Article Link
- News Article Link
- News Article Link</p>
<p><strong>MONDAY, JUNE 22, 2015 (3 posts)</strong>
- News Article Link
- News Article Link
- News Article Link</p>
<p>...I can't find info anywhere on Google. Hoping this is possible. Thanks to anyone who can help.</p>
<p>Justin.</p>
|
[
{
"answer_id": 192480,
"author": "Nia Skywalk",
"author_id": 74433,
"author_profile": "https://wordpress.stackexchange.com/users/74433",
"pm_score": 2,
"selected": true,
"text": "<p>Initially, I saw the double and single quotes all jumbled up. This did fix some of what I saw, but I finally had time to test the code you put up.</p>\n\n<p>First step, I used <code>var_dump</code> on <code>$recent_posts</code> to make sure I was getting the usable values.</p>\n\n<p>Next, I echoed each variable as it was called, to make sure I knew what was being generated. I discovered that this line, as @james-barrett said, was not calling correct information:</p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($post->ID);\n</code></pre>\n\n<p>So, I used @james-barrett's suggestion and changed it to: </p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($recent[\"ID\"]);\n</code></pre>\n\n<p>Which then worked to get the correct ID.</p>\n\n<p>After I was calling the correct information, the <code>url()</code> portion was filling correctly, but the next problem was getting the correct size called.</p>\n\n<p>I did some research and discovered how the files were saved in the 'uploads' folder and then continued on to search for a way to access a function that would allow me to reach the one labled \"thumbnail\". The solution I found might not work with other sizes, or perhaps you could do more research after this, but I changed the <code>$post_thumbnail_url</code> variable to this:</p>\n\n<pre><code>$post_thumbnail_url = wp_get_attachment_thumb_url( $post_thumbnail_id );\n</code></pre>\n\n<p>Which resulted in the 150x150 image being called.</p>\n\n<p>After all was said and done, I converted your <strong>broken code</strong> above to this working code:</p>\n\n<pre><code><?php \n$args = array( 'numberposts' => '2' );\n$recent_posts = wp_get_recent_posts( $args );\nforeach( $recent_posts as $recent ){\n $post_thumbnail_id = get_post_thumbnail_id($recent[\"ID\"]);\n $post_thumbnail_url = wp_get_attachment_thumb_url( $post_thumbnail_id );\n echo '<div class=\"post\">';\n echo '<div class=\"post_thumb\" style=\"background-image:url(\\''.$post_thumbnail_url.'\\')\"></div>';\n echo '<div class=\"content\"';\n echo '<h2 class=\"post_title\">';\n echo '<a href=\"'.get_permalink($recent[\"ID\"]).'\" title=\"'.$recent[\"post_title\"].'\" >'.$recent[\"post_title\"].'</a>';\n echo '</h2>';\n echo '<p class=\"post_excerpt\">'.$recent[\"post_excerpt\"].'</p>';\n echo '</div>'; //content\n echo '</div>'; //.post\n }\n?>\n</code></pre>\n\n<p>Note: I adjusted the url() to be url('') because some of my older browsers require the single quotes, but I suspect you can remove them.</p>\n"
},
{
"answer_id": 192498,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 0,
"selected": false,
"text": "<p>I think the issue is with the following line of code:</p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($post->ID);\n</code></pre>\n\n<p>It should be the ID of your <code>$recent</code> variable not <code>$post</code>.</p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($recent->ID);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$post_thumbnail_id = get_post_thumbnail_id($recent['ID']);\n</code></pre>\n\n<p>and to get a specific size of thumbnail you could do something like this:</p>\n\n<pre><code><?php\n foreach( $recent_posts as $recent ){\n $post_thumbnail_id = get_post_thumbnail_id($recent['ID']);\n $post_thumbnail_url = wp_get_attachment_image_src($post_thumbnail_id, 'thumbnail' );\n\n echo '<div class=\"post\">';\n echo '<div class=\"post_thumb\" style=\"background-image:url('.$post_thumbnail_url.')\"></div>';\n echo '<div class=\"content\"';\n echo '<h2 class=\"post_title\">';\n echo '<a href=\"'.get_permalink($recent[\"ID\"]).'\" title=\"'.$recent[\"post_title\"].'\" >'.$recent[\"post_title\"].'</a>';\n echo '</h2>';\n echo '<p class=\"post_excerpt\">'.$recent[\"post_excerpt\"].'</p>';\n echo '</div>'; //content\n echo '</div>'; //.post\n\n }\n?>\n</code></pre>\n"
}
] |
2015/06/24
|
[
"https://wordpress.stackexchange.com/questions/192488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75164/"
] |
I am building a site client who makes anywhere from 20-50 news posts per day. I'd like to have a news feed where it shows the date / post count as an H3 and then list all the posts for that day underneath.
Example...
**TODAY (4 posts)**
- News Article Link
- News Article Link
- News Article Link
- News Article Link
**YESTERDAY (6 posts)**
- News Article Link
- News Article Link
- News Article Link
- News Article Link
- News Article Link
- News Article Link
**MONDAY, JUNE 22, 2015 (3 posts)**
- News Article Link
- News Article Link
- News Article Link
...I can't find info anywhere on Google. Hoping this is possible. Thanks to anyone who can help.
Justin.
|
Initially, I saw the double and single quotes all jumbled up. This did fix some of what I saw, but I finally had time to test the code you put up.
First step, I used `var_dump` on `$recent_posts` to make sure I was getting the usable values.
Next, I echoed each variable as it was called, to make sure I knew what was being generated. I discovered that this line, as @james-barrett said, was not calling correct information:
```
$post_thumbnail_id = get_post_thumbnail_id($post->ID);
```
So, I used @james-barrett's suggestion and changed it to:
```
$post_thumbnail_id = get_post_thumbnail_id($recent["ID"]);
```
Which then worked to get the correct ID.
After I was calling the correct information, the `url()` portion was filling correctly, but the next problem was getting the correct size called.
I did some research and discovered how the files were saved in the 'uploads' folder and then continued on to search for a way to access a function that would allow me to reach the one labled "thumbnail". The solution I found might not work with other sizes, or perhaps you could do more research after this, but I changed the `$post_thumbnail_url` variable to this:
```
$post_thumbnail_url = wp_get_attachment_thumb_url( $post_thumbnail_id );
```
Which resulted in the 150x150 image being called.
After all was said and done, I converted your **broken code** above to this working code:
```
<?php
$args = array( 'numberposts' => '2' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$post_thumbnail_id = get_post_thumbnail_id($recent["ID"]);
$post_thumbnail_url = wp_get_attachment_thumb_url( $post_thumbnail_id );
echo '<div class="post">';
echo '<div class="post_thumb" style="background-image:url(\''.$post_thumbnail_url.'\')"></div>';
echo '<div class="content"';
echo '<h2 class="post_title">';
echo '<a href="'.get_permalink($recent["ID"]).'" title="'.$recent["post_title"].'" >'.$recent["post_title"].'</a>';
echo '</h2>';
echo '<p class="post_excerpt">'.$recent["post_excerpt"].'</p>';
echo '</div>'; //content
echo '</div>'; //.post
}
?>
```
Note: I adjusted the url() to be url('') because some of my older browsers require the single quotes, but I suspect you can remove them.
|
192,496 |
<p>I'm creating a custom walker menu where I'm adding custom fields to the menu items, but I would like the fields to be specific to menu locations. I can get all the menu locations with the menu ID's assigned to them from:</p>
<pre><code>$menu_locations = get_nav_menu_locations();
</code></pre>
<p>This outputs an array like: </p>
<pre><code>array:2 [
"main_nav" => 27
"footer_nav" => 29
]
</code></pre>
<p>Or you can get all the menus but they don't have the theme locations with: </p>
<pre><code>$menus = get_terms('nav_menu');
</code></pre>
<p>This outputs an an object list like: </p>
<pre><code>array:3 [
0 => {#762
+"term_id": "28"
+"name": "Footer Menu"
+"slug": "footer-menu"
+"term_group": "0"
+"term_taxonomy_id": "28"
+"taxonomy": "nav_menu"
+"description": ""
+"parent": "0"
+"count": "1"
}
1 => {#761
+"term_id": "27"
+"name": "Menu 1"
+"slug": "menu-1"
+"term_group": "0"
+"term_taxonomy_id": "27"
+"taxonomy": "nav_menu"
+"description": ""
+"parent": "0"
+"count": "11"
}
]
</code></pre>
<p>My question is: Can you get the menu location of a specific menu by ID / name / slug? Or can you get the menu location by menu ID?</p>
|
[
{
"answer_id": 192497,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": -1,
"selected": false,
"text": "<p>wp_get_nav_menu_object( $menu );</p>\n\n<blockquote>\n <p>Returns nav menu object when given a menu id, slug, or name. This is\n particularly useful for retrieving the name assigned to the custom\n menu.</p>\n</blockquote>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_object\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_object</a></p>\n"
},
{
"answer_id": 192590,
"author": "Aurelian Pop",
"author_id": 75163,
"author_profile": "https://wordpress.stackexchange.com/users/75163",
"pm_score": 0,
"selected": false,
"text": "<p>I found the solution for this issue and I'm going to post it here maybe someone else needs to add custom fields to the backend menu themselves. The best way of doing this as i found out is to call a different walker class for each backend menu.</p>\n\n<p>This will be a long answer and i couldn't post all the code because of characters limitations but if you follow it closely you'll see that it's only missing the second Walker class which is exactly the same as the first one but with the differences posted here</p>\n\n<p>The answer is based on this answer</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/33495/75163\">https://wordpress.stackexchange.com/a/33495/75163</a></p>\n\n<p>First create the two (or moore) menu locations: </p>\n\n<pre><code>register_nav_menus([\n 'main_nav' => __('Main nav menu', 'textdomain'),\n 'footer_nav' => __('Footer nav menu', 'textdomain'),\n]);\n</code></pre>\n\n<p>Then Create your nav menus which you're going to use on your menu locations:</p>\n\n<pre><code> $args = array(\n 'theme_location' => 'main_nav',\n 'menu' => '',\n 'container' => 'div',\n 'container_id' => '',\n 'menu_class' => 'menu',\n 'menu_id' => '',\n 'echo' => true,\n 'fallback_cb' => 'wp_page_menu',\n 'before' => '',\n 'after' => '',\n 'link_before' => '',\n 'link_after' => '',\n 'items_wrap' => '<ul role=\"navigation\" id=\"nav-primary\" class=\"nav\">%3$s</ul>',\n 'depth' => 3,\n );\n\n wp_nav_menu($args);\n</code></pre>\n\n<p><strong>AND:</strong> </p>\n\n<pre><code>$args = array(\n 'theme_location' => 'footer_nav',\n 'menu' => '',\n 'container' => '',\n 'container_id' => '',\n 'menu_class' => 'menu',\n 'menu_id' => '',\n 'echo' => true,\n 'fallback_cb' => 'wp_page_menu',\n 'before' => '',\n 'after' => '',\n 'link_before' => '',\n 'link_after' => '',\n 'items_wrap' => '%3$s',\n 'depth' => 2,\n );\n\n wp_nav_menu($args);\n</code></pre>\n\n<p>Select them in the menu locations section in Appearance -> Menus -> Manage Locations.</p>\n\n<p>Now start creating your walker based on the example on top (this goes in your functions.php file):</p>\n\n<pre><code>/**\n * Saves new field to postmeta for navigation\n */\nadd_action('wp_update_nav_menu_item', 'custom_nav_update', 10, 3);\nfunction custom_nav_update($menu_id, $menu_item_db_id, $args)\n{ \n if (isset($_REQUEST['menu-item-custom']) && is_array($_REQUEST['menu-item-custom'])) {\n if (isset($_REQUEST['menu-item-custom'][$menu_item_db_id])) {\n $custom_value = $_REQUEST['menu-item-custom'][$menu_item_db_id];\n update_post_meta($menu_item_db_id, '_menu_item_custom', $custom_value);\n } else {\n $post_meta = get_post_meta($menu_item_db_id, '_menu_item_custom', true);\n if ($post_meta == \"checked\") {\n delete_post_meta($menu_item_db_id, '_menu_item_custom');\n }\n }\n }\n\n if (isset($_REQUEST['menu-item-icon']) && is_array($_REQUEST['menu-item-icon'])) {\n if (isset($_REQUEST['menu-item-icon'][$menu_item_db_id])) {\n $custom_value = $_REQUEST['menu-item-icon'][$menu_item_db_id];\n update_post_meta($menu_item_db_id, '_menu_item_icon', $custom_value);\n } else {\n $post_meta = get_post_meta($menu_item_db_id, '_menu_item_icon', true);\n $icons = lpCustomIconsList();\n foreach($icons as $icon => $icon_name)\n if ($post_meta == $icon) {\n delete_post_meta($menu_item_db_id, '_menu_item_icon');\n }\n }\n }\n}\n\n/**\n * Adds values of new field to $item object that will be passed to Walker_Nav_Menu_Edit_Custom\n * @param int $menu_item item id\n * @return obj the whole item\n */\nadd_filter( 'wp_setup_nav_menu_item','custom_nav_item' );\nfunction custom_nav_item($menu_item) {\n $menu_item->custom = get_post_meta( $menu_item->ID, '_menu_item_custom', true );\n $menu_item->icon = get_post_meta( $menu_item->ID, '_menu_item_icon', true );\n return $menu_item;\n}\n\n/**\n * Creates a menu walker with custom Checkbox or Select box \n *\n * @param $walker\n * @param $menu_id\n * @return string\n */\nadd_filter( 'wp_edit_nav_menu_walker', 'custom_nav_edit_walker',10,2 );\nfunction custom_nav_edit_walker($walker,$menu_id) {\n $menu_locations = get_nav_menu_locations();\n\n $main_nav_obj = get_term( $menu_locations['main_nav'], 'nav_menu' );\n $footer_nav_obj = get_term( $menu_locations['footer_nav'], 'nav_menu' );\n if($main_nav_obj->term_id == $menu_id) {\n return 'BackendHeader';\n } elseif($footer_nav_obj->term_id == $menu_id) {\n return 'BackendFooter';\n } else {\n return $walker;\n }\n\n}\n</code></pre>\n\n<p>These wakers are based on the Walker_Nav_Menu_Edit class</p>\n\n<pre><code>class BackendHeader extends Walker_Nav_Menu_Edit\n{\n\n\n /**\n * @see Walker::start_el()\n * @since 3.0.0\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array|object $args\n * @param int $id\n */\n function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 )\n { global $_wp_nav_menu_max_depth;\n $_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth;\n\n $indent = ($depth) ? str_repeat(\"\\t\", $depth) : '';\n\n ob_start();\n $item_id = esc_attr($item->ID);\n $removed_args = array(\n 'action',\n 'customlink-tab',\n 'edit-menu-item',\n 'menu-item',\n 'page-tab',\n '_wpnonce',\n );\n\n $original_title = '';\n if ('taxonomy' == $item->type) {\n $original_title = get_term_field('name', $item->object_id, $item->object, 'raw');\n if (is_wp_error($original_title))\n $original_title = false;\n } elseif ('post_type' == $item->type) {\n $original_object = get_post($item->object_id);\n $original_title = $original_object->post_title;\n }\n\n $classes = array(\n 'menu-item menu-item-depth-' . $depth,\n 'menu-item-' . esc_attr($item->object),\n 'menu-item-edit-' . ((isset($_GET['edit-menu-item']) && $item_id == $_GET['edit-menu-item']) ? 'active' : 'inactive'),\n );\n\n $title = $item->title;\n\n if (!empty($item->_invalid)) {\n $classes[] = 'menu-item-invalid';\n /* translators: %s: title of menu item which is invalid */\n $title = sprintf(__('%s (Invalid)'), $item->title);\n } elseif (isset($item->post_status) && 'draft' == $item->post_status) {\n $classes[] = 'pending';\n /* translators: %s: title of menu item in draft status */\n $title = sprintf(__('%s (Pending)'), $item->title);\n }\n\n $title = empty($item->label) ? $title : $item->label;\n ?>\n <li id=\"menu-item-<?php echo $item_id; ?>\" class=\"<?php echo implode(' ', $classes); ?>\">\n <dl class=\"menu-item-bar\">\n <dt class=\"menu-item-handle\">\n <span class=\"item-title\"><?php echo esc_html($title); ?></span>\n <span class=\"item-controls\">\n <span class=\"item-type\"><?php echo esc_html($item->type_label); ?></span>\n <span class=\"item-order hide-if-js\">\n <a href=\"<?php\n echo wp_nonce_url(\n add_query_arg(\n array(\n 'action' => 'move-up-menu-item',\n 'menu-item' => $item_id,\n ),\n remove_query_arg($removed_args, admin_url('nav-menus.php'))\n ),\n 'move-menu_item'\n );\n ?>\" class=\"item-move-up\"><abbr title=\"<?php esc_attr_e('Move up'); ?>\">&#8593;</abbr></a>\n |\n <a href=\"<?php\n echo wp_nonce_url(\n add_query_arg(\n array(\n 'action' => 'move-down-menu-item',\n 'menu-item' => $item_id,\n ),\n remove_query_arg($removed_args, admin_url('nav-menus.php'))\n ),\n 'move-menu_item'\n );\n ?>\" class=\"item-move-down\"><abbr title=\"<?php esc_attr_e('Move down'); ?>\">&#8595;</abbr></a>\n </span>\n <a class=\"item-edit\" id=\"edit-<?php echo $item_id; ?>\"\n title=\"<?php esc_attr_e('Edit Menu Item'); ?>\" href=\"<?php\n echo (isset($_GET['edit-menu-item']) && $item_id == $_GET['edit-menu-item']) ? admin_url('nav-menus.php') : add_query_arg('edit-menu-item', $item_id, remove_query_arg($removed_args, admin_url('nav-menus.php#menu-item-settings-' . $item_id)));\n ?>\"><?php _e('Edit Menu Item'); ?></a>\n </span>\n </dt>\n </dl>\n\n <div class=\"menu-item-settings\" id=\"menu-item-settings-<?php echo $item_id; ?>\">\n <?php if ('custom' == $item->type) : ?>\n <p class=\"field-url description description-wide\">\n <label for=\"edit-menu-item-url-<?php echo $item_id; ?>\">\n <?php _e('URL'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-url-<?php echo $item_id; ?>\"\n class=\"widefat code edit-menu-item-url\" name=\"menu-item-url[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->url); ?>\"/>\n </label>\n </p>\n <?php endif; ?>\n <p class=\"description description-thin\">\n <label for=\"edit-menu-item-title-<?php echo $item_id; ?>\">\n <?php _e('Navigation Label'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-title-<?php echo $item_id; ?>\"\n class=\"widefat edit-menu-item-title\" name=\"menu-item-title[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->title); ?>\"/>\n </label>\n </p>\n\n <p class=\"description description-thin\">\n <label for=\"edit-menu-item-attr-title-<?php echo $item_id; ?>\">\n <?php _e('Title Attribute'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-attr-title-<?php echo $item_id; ?>\"\n class=\"widefat edit-menu-item-attr-title\"\n name=\"menu-item-attr-title[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->post_excerpt); ?>\"/>\n </label>\n </p>\n\n <p class=\"field-link-target description\">\n <label for=\"edit-menu-item-target-<?php echo $item_id; ?>\">\n <input type=\"checkbox\" id=\"edit-menu-item-target-<?php echo $item_id; ?>\" value=\"_blank\"\n name=\"menu-item-target[<?php echo $item_id; ?>]\"<?php checked($item->target, '_blank'); ?> />\n <?php _e('Open link in a new window/tab'); ?>\n </label>\n </p>\n\n <p class=\"field-css-classes description description-thin\">\n <label for=\"edit-menu-item-classes-<?php echo $item_id; ?>\">\n <?php _e('CSS Classes (optional)'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-classes-<?php echo $item_id; ?>\"\n class=\"widefat code edit-menu-item-classes\" name=\"menu-item-classes[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr(implode(' ', $item->classes)); ?>\"/>\n </label>\n </p>\n\n <p class=\"field-xfn description description-thin\">\n <label for=\"edit-menu-item-xfn-<?php echo $item_id; ?>\">\n <?php _e('Link Relationship (XFN)'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-xfn-<?php echo $item_id; ?>\"\n class=\"widefat code edit-menu-item-xfn\" name=\"menu-item-xfn[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->xfn); ?>\"/>\n </label>\n </p>\n\n <p class=\"field-description description description-wide\">\n <label for=\"edit-menu-item-description-<?php echo $item_id; ?>\">\n <?php _e('Description'); ?><br/>\n <textarea id=\"edit-menu-item-description-<?php echo $item_id; ?>\"\n class=\"widefat edit-menu-item-description\" rows=\"3\" cols=\"20\"\n name=\"menu-item-description[<?php echo $item_id; ?>]\"><?php echo esc_html($item->description); // textarea_escaped\n ?></textarea>\n <span\n class=\"description\"><?php _e('The description will be displayed in the menu if the current theme supports it.'); ?></span>\n </label>\n </p>\n <?php\n /*\n * This is the added field\n */\n ?>\n <p class=\"field-custom description description-wide\">\n <label for=\"edit-menu-item-custom-<?php echo $item_id; ?>\">\n <?php _e('Checkbox'); ?><br/>\n <input type=\"checkbox\" id=\"edit-menu-item-custom-<?php echo $item_id; ?>\"\n class=\"widefat code edit-menu-item-custom\"\n name=\"menu-item-custom[<?php echo $item_id; ?>]\" <?php if ($item->custom == 'checked') {\n echo \"checked\";\n } ?> value=\"checked\"/>\n </label>\n </p>\n <?php\n /*\n * end added field\n */\n ?>\n <div class=\"menu-item-actions description-wide submitbox\">\n <?php if ('custom' != $item->type && $original_title !== false) : ?>\n <p class=\"link-to-original\">\n <?php printf(__('Original: %s'), '<a href=\"' . esc_attr($item->url) . '\">' . esc_html($original_title) . '</a>'); ?>\n </p>\n <?php endif; ?>\n <a class=\"item-delete submitdelete deletion\" id=\"delete-<?php echo $item_id; ?>\" href=\"<?php\n echo wp_nonce_url(\n add_query_arg(\n array(\n 'action' => 'delete-menu-item',\n 'menu-item' => $item_id,\n ),\n remove_query_arg($removed_args, admin_url('nav-menus.php'))\n ),\n 'delete-menu_item_' . $item_id\n ); ?>\"><?php _e('Remove'); ?></a> <span class=\"meta-sep\"> | </span> <a class=\"item-cancel submitcancel\"\n id=\"cancel-<?php echo $item_id; ?>\"\n href=\"<?php echo esc_url(add_query_arg(array('edit-menu-item' => $item_id, 'cancel' => time()), remove_query_arg($removed_args, admin_url('nav-menus.php'))));\n ?>#menu-item-settings-<?php echo $item_id; ?>\"><?php _e('Cancel'); ?></a>\n </div>\n\n <input class=\"menu-item-data-db-id\" type=\"hidden\" name=\"menu-item-db-id[<?php echo $item_id; ?>]\"\n value=\"<?php echo $item_id; ?>\"/>\n <input class=\"menu-item-data-object-id\" type=\"hidden\" name=\"menu-item-object-id[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->object_id); ?>\"/>\n <input class=\"menu-item-data-object\" type=\"hidden\" name=\"menu-item-object[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->object); ?>\"/>\n <input class=\"menu-item-data-parent-id\" type=\"hidden\" name=\"menu-item-parent-id[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->menu_item_parent); ?>\"/>\n <input class=\"menu-item-data-position\" type=\"hidden\" name=\"menu-item-position[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->menu_order); ?>\"/>\n <input class=\"menu-item-data-type\" type=\"hidden\" name=\"menu-item-type[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->type); ?>\"/>\n </div>\n <!-- .menu-item-settings-->\n <ul class=\"menu-item-transport\"></ul>\n <?php\n $output .= ob_get_clean();\n }\n}\n/**\n* The same as the one on top but with a different fiel\n*/\nclass BackendFooter extends Walker_Nav_Menu_Edit\n{\n\n /*\n * This is the added field\n */\n ?>\n <p class=\"field-icon description description-wide\">\n <label for=\"edit-menu-item-icon-<?php echo $item_id; ?>\">\n <?php _e('Icon'); ?><br/>\n <select id=\"edit-menu-item-icon-<?php echo $item_id; ?>\" class=\"widefat code edit-menu-item-icon\" name=\"menu-item-icon[<?php echo $item_id; ?>]\">\n <option <?php if('icon' == $item->icon) { echo \"selected='selected'\"; } ?> value=\"icon\">Icon One</option>\n<option <?php if('icon2' == $item->icon) { echo \"selected='selected'\"; } ?> value=\"icon2\">Icon Two</option>\n<option <?php if('icon3' == $item->icon) { echo \"selected='selected'\"; } ?> value=\"icon3\">Icon Three</option>\n <?php } ?>\n </select>\n </label>\n </p>\n <?php\n /*\n * end added field\n */\n ?>\n\n}\n</code></pre>\n"
},
{
"answer_id": 331910,
"author": "anastymous",
"author_id": 51205,
"author_profile": "https://wordpress.stackexchange.com/users/51205",
"pm_score": 1,
"selected": false,
"text": "<p>You'll find it much easier to control which fields are shown, by controlling which walker is used. Rather than trying to 'toggle' the fields inside the walker.</p>\n\n<p>I also wanted to show a bunch of custom fields, and only show them on a menu at a particular menu location. So I used the following...</p>\n\n<pre><code>add_filter( 'wp_edit_nav_menu_walker', function( $walker, $menu_id ) {\n\n $menu_locations = get_nav_menu_locations();\n\n if ( $menu_locations['main_menu'] == $menu_id ) {\n return 'Walker_Nav_Menu_Custom';\n } else {\n return $walker;\n }\n\n}, 10, 2); \n</code></pre>\n"
},
{
"answer_id": 398523,
"author": "Jake",
"author_id": 64348,
"author_profile": "https://wordpress.stackexchange.com/users/64348",
"pm_score": 0,
"selected": false,
"text": "<p>Simply transposing the array returned by <code>get_nav_menu_locations()</code> gives you a mapping from menu ID to menu location:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$menu_locations = \\array_flip(\\get_nav_menu_locations());\n$menu_location = $menu_locations[$menu_id] ?? null; \nif ($menu_location === 'main_nav') {\n do_something();\n}\n</code></pre>\n<p>This above code includes getting the menu location of a specific menu by ID.</p>\n<p>If you don't have a menu ID but instead have the name or slug, you can use <code>wp_get_nav_menu_object()</code> first to get the ID:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$menu_term = \\wp_get_nav_menu_object($menu_slug_name_id_or_wpterm);\n$menu_id = \\is_object($menu_term) ? $menu_term->term_id : null;\n</code></pre>\n<p>Then continue with the code above to get the location from the ID.</p>\n<p>(<code>wp_get_nav_menu_object()</code> will also accept an ID or <code>WP_Term</code>, so you can throw whatever you have at it to get a <code>WP_Term</code> to get the ID.)</p>\n"
}
] |
2015/06/24
|
[
"https://wordpress.stackexchange.com/questions/192496",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75163/"
] |
I'm creating a custom walker menu where I'm adding custom fields to the menu items, but I would like the fields to be specific to menu locations. I can get all the menu locations with the menu ID's assigned to them from:
```
$menu_locations = get_nav_menu_locations();
```
This outputs an array like:
```
array:2 [
"main_nav" => 27
"footer_nav" => 29
]
```
Or you can get all the menus but they don't have the theme locations with:
```
$menus = get_terms('nav_menu');
```
This outputs an an object list like:
```
array:3 [
0 => {#762
+"term_id": "28"
+"name": "Footer Menu"
+"slug": "footer-menu"
+"term_group": "0"
+"term_taxonomy_id": "28"
+"taxonomy": "nav_menu"
+"description": ""
+"parent": "0"
+"count": "1"
}
1 => {#761
+"term_id": "27"
+"name": "Menu 1"
+"slug": "menu-1"
+"term_group": "0"
+"term_taxonomy_id": "27"
+"taxonomy": "nav_menu"
+"description": ""
+"parent": "0"
+"count": "11"
}
]
```
My question is: Can you get the menu location of a specific menu by ID / name / slug? Or can you get the menu location by menu ID?
|
You'll find it much easier to control which fields are shown, by controlling which walker is used. Rather than trying to 'toggle' the fields inside the walker.
I also wanted to show a bunch of custom fields, and only show them on a menu at a particular menu location. So I used the following...
```
add_filter( 'wp_edit_nav_menu_walker', function( $walker, $menu_id ) {
$menu_locations = get_nav_menu_locations();
if ( $menu_locations['main_menu'] == $menu_id ) {
return 'Walker_Nav_Menu_Custom';
} else {
return $walker;
}
}, 10, 2);
```
|
192,513 |
<p>I'm looking for some help in creating a query based on fields I made in Advanced Custom Fields. I'd like to create a query that would loop through a custom post type, using arguments such as:</p>
<pre><code>?genre=Dance&keyword=&mood=&album=
</code></pre>
<p>What I expect from this query is all posts with the <code>genre</code> meta-field of "Dance" to be posted. Since all of the other arguments have no value, I'm expecting these to be ignored in the query. If the arguments change to:</p>
<pre><code>?genre=Dance&keyword=&mood=happy&album=
</code></pre>
<p>I want the query to narrow down and only find posts with the <code>genre</code> meta-field of "Dance" and the <code>mood</code> meta-field of "Happy".</p>
<p>Here's the code I'm using that gives me some of the results. The only way to add my mood variable to the query is if I use 'AND' as the relation and add it as another array, but then I lose being able to just query using one argument. </p>
<pre><code>$queryGenre = $_GET['genre'];
$paged = get_query_var( 'paged' );
$loop = new WP_Query( array(
'posts_per_page' => 5,
'post_type' => 'catalog',
'paged' => $paged,
'order_by' => 'ASC',
'meta_query' => array(
array(
'key' => 'genre',
'value' => $queryGenre,
'compare' => '=',
)
)
) );
while ( $loop->have_posts() ) : $loop->the_post();
</code></pre>
|
[
{
"answer_id": 192497,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": -1,
"selected": false,
"text": "<p>wp_get_nav_menu_object( $menu );</p>\n\n<blockquote>\n <p>Returns nav menu object when given a menu id, slug, or name. This is\n particularly useful for retrieving the name assigned to the custom\n menu.</p>\n</blockquote>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_object\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_object</a></p>\n"
},
{
"answer_id": 192590,
"author": "Aurelian Pop",
"author_id": 75163,
"author_profile": "https://wordpress.stackexchange.com/users/75163",
"pm_score": 0,
"selected": false,
"text": "<p>I found the solution for this issue and I'm going to post it here maybe someone else needs to add custom fields to the backend menu themselves. The best way of doing this as i found out is to call a different walker class for each backend menu.</p>\n\n<p>This will be a long answer and i couldn't post all the code because of characters limitations but if you follow it closely you'll see that it's only missing the second Walker class which is exactly the same as the first one but with the differences posted here</p>\n\n<p>The answer is based on this answer</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/33495/75163\">https://wordpress.stackexchange.com/a/33495/75163</a></p>\n\n<p>First create the two (or moore) menu locations: </p>\n\n<pre><code>register_nav_menus([\n 'main_nav' => __('Main nav menu', 'textdomain'),\n 'footer_nav' => __('Footer nav menu', 'textdomain'),\n]);\n</code></pre>\n\n<p>Then Create your nav menus which you're going to use on your menu locations:</p>\n\n<pre><code> $args = array(\n 'theme_location' => 'main_nav',\n 'menu' => '',\n 'container' => 'div',\n 'container_id' => '',\n 'menu_class' => 'menu',\n 'menu_id' => '',\n 'echo' => true,\n 'fallback_cb' => 'wp_page_menu',\n 'before' => '',\n 'after' => '',\n 'link_before' => '',\n 'link_after' => '',\n 'items_wrap' => '<ul role=\"navigation\" id=\"nav-primary\" class=\"nav\">%3$s</ul>',\n 'depth' => 3,\n );\n\n wp_nav_menu($args);\n</code></pre>\n\n<p><strong>AND:</strong> </p>\n\n<pre><code>$args = array(\n 'theme_location' => 'footer_nav',\n 'menu' => '',\n 'container' => '',\n 'container_id' => '',\n 'menu_class' => 'menu',\n 'menu_id' => '',\n 'echo' => true,\n 'fallback_cb' => 'wp_page_menu',\n 'before' => '',\n 'after' => '',\n 'link_before' => '',\n 'link_after' => '',\n 'items_wrap' => '%3$s',\n 'depth' => 2,\n );\n\n wp_nav_menu($args);\n</code></pre>\n\n<p>Select them in the menu locations section in Appearance -> Menus -> Manage Locations.</p>\n\n<p>Now start creating your walker based on the example on top (this goes in your functions.php file):</p>\n\n<pre><code>/**\n * Saves new field to postmeta for navigation\n */\nadd_action('wp_update_nav_menu_item', 'custom_nav_update', 10, 3);\nfunction custom_nav_update($menu_id, $menu_item_db_id, $args)\n{ \n if (isset($_REQUEST['menu-item-custom']) && is_array($_REQUEST['menu-item-custom'])) {\n if (isset($_REQUEST['menu-item-custom'][$menu_item_db_id])) {\n $custom_value = $_REQUEST['menu-item-custom'][$menu_item_db_id];\n update_post_meta($menu_item_db_id, '_menu_item_custom', $custom_value);\n } else {\n $post_meta = get_post_meta($menu_item_db_id, '_menu_item_custom', true);\n if ($post_meta == \"checked\") {\n delete_post_meta($menu_item_db_id, '_menu_item_custom');\n }\n }\n }\n\n if (isset($_REQUEST['menu-item-icon']) && is_array($_REQUEST['menu-item-icon'])) {\n if (isset($_REQUEST['menu-item-icon'][$menu_item_db_id])) {\n $custom_value = $_REQUEST['menu-item-icon'][$menu_item_db_id];\n update_post_meta($menu_item_db_id, '_menu_item_icon', $custom_value);\n } else {\n $post_meta = get_post_meta($menu_item_db_id, '_menu_item_icon', true);\n $icons = lpCustomIconsList();\n foreach($icons as $icon => $icon_name)\n if ($post_meta == $icon) {\n delete_post_meta($menu_item_db_id, '_menu_item_icon');\n }\n }\n }\n}\n\n/**\n * Adds values of new field to $item object that will be passed to Walker_Nav_Menu_Edit_Custom\n * @param int $menu_item item id\n * @return obj the whole item\n */\nadd_filter( 'wp_setup_nav_menu_item','custom_nav_item' );\nfunction custom_nav_item($menu_item) {\n $menu_item->custom = get_post_meta( $menu_item->ID, '_menu_item_custom', true );\n $menu_item->icon = get_post_meta( $menu_item->ID, '_menu_item_icon', true );\n return $menu_item;\n}\n\n/**\n * Creates a menu walker with custom Checkbox or Select box \n *\n * @param $walker\n * @param $menu_id\n * @return string\n */\nadd_filter( 'wp_edit_nav_menu_walker', 'custom_nav_edit_walker',10,2 );\nfunction custom_nav_edit_walker($walker,$menu_id) {\n $menu_locations = get_nav_menu_locations();\n\n $main_nav_obj = get_term( $menu_locations['main_nav'], 'nav_menu' );\n $footer_nav_obj = get_term( $menu_locations['footer_nav'], 'nav_menu' );\n if($main_nav_obj->term_id == $menu_id) {\n return 'BackendHeader';\n } elseif($footer_nav_obj->term_id == $menu_id) {\n return 'BackendFooter';\n } else {\n return $walker;\n }\n\n}\n</code></pre>\n\n<p>These wakers are based on the Walker_Nav_Menu_Edit class</p>\n\n<pre><code>class BackendHeader extends Walker_Nav_Menu_Edit\n{\n\n\n /**\n * @see Walker::start_el()\n * @since 3.0.0\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array|object $args\n * @param int $id\n */\n function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 )\n { global $_wp_nav_menu_max_depth;\n $_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth;\n\n $indent = ($depth) ? str_repeat(\"\\t\", $depth) : '';\n\n ob_start();\n $item_id = esc_attr($item->ID);\n $removed_args = array(\n 'action',\n 'customlink-tab',\n 'edit-menu-item',\n 'menu-item',\n 'page-tab',\n '_wpnonce',\n );\n\n $original_title = '';\n if ('taxonomy' == $item->type) {\n $original_title = get_term_field('name', $item->object_id, $item->object, 'raw');\n if (is_wp_error($original_title))\n $original_title = false;\n } elseif ('post_type' == $item->type) {\n $original_object = get_post($item->object_id);\n $original_title = $original_object->post_title;\n }\n\n $classes = array(\n 'menu-item menu-item-depth-' . $depth,\n 'menu-item-' . esc_attr($item->object),\n 'menu-item-edit-' . ((isset($_GET['edit-menu-item']) && $item_id == $_GET['edit-menu-item']) ? 'active' : 'inactive'),\n );\n\n $title = $item->title;\n\n if (!empty($item->_invalid)) {\n $classes[] = 'menu-item-invalid';\n /* translators: %s: title of menu item which is invalid */\n $title = sprintf(__('%s (Invalid)'), $item->title);\n } elseif (isset($item->post_status) && 'draft' == $item->post_status) {\n $classes[] = 'pending';\n /* translators: %s: title of menu item in draft status */\n $title = sprintf(__('%s (Pending)'), $item->title);\n }\n\n $title = empty($item->label) ? $title : $item->label;\n ?>\n <li id=\"menu-item-<?php echo $item_id; ?>\" class=\"<?php echo implode(' ', $classes); ?>\">\n <dl class=\"menu-item-bar\">\n <dt class=\"menu-item-handle\">\n <span class=\"item-title\"><?php echo esc_html($title); ?></span>\n <span class=\"item-controls\">\n <span class=\"item-type\"><?php echo esc_html($item->type_label); ?></span>\n <span class=\"item-order hide-if-js\">\n <a href=\"<?php\n echo wp_nonce_url(\n add_query_arg(\n array(\n 'action' => 'move-up-menu-item',\n 'menu-item' => $item_id,\n ),\n remove_query_arg($removed_args, admin_url('nav-menus.php'))\n ),\n 'move-menu_item'\n );\n ?>\" class=\"item-move-up\"><abbr title=\"<?php esc_attr_e('Move up'); ?>\">&#8593;</abbr></a>\n |\n <a href=\"<?php\n echo wp_nonce_url(\n add_query_arg(\n array(\n 'action' => 'move-down-menu-item',\n 'menu-item' => $item_id,\n ),\n remove_query_arg($removed_args, admin_url('nav-menus.php'))\n ),\n 'move-menu_item'\n );\n ?>\" class=\"item-move-down\"><abbr title=\"<?php esc_attr_e('Move down'); ?>\">&#8595;</abbr></a>\n </span>\n <a class=\"item-edit\" id=\"edit-<?php echo $item_id; ?>\"\n title=\"<?php esc_attr_e('Edit Menu Item'); ?>\" href=\"<?php\n echo (isset($_GET['edit-menu-item']) && $item_id == $_GET['edit-menu-item']) ? admin_url('nav-menus.php') : add_query_arg('edit-menu-item', $item_id, remove_query_arg($removed_args, admin_url('nav-menus.php#menu-item-settings-' . $item_id)));\n ?>\"><?php _e('Edit Menu Item'); ?></a>\n </span>\n </dt>\n </dl>\n\n <div class=\"menu-item-settings\" id=\"menu-item-settings-<?php echo $item_id; ?>\">\n <?php if ('custom' == $item->type) : ?>\n <p class=\"field-url description description-wide\">\n <label for=\"edit-menu-item-url-<?php echo $item_id; ?>\">\n <?php _e('URL'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-url-<?php echo $item_id; ?>\"\n class=\"widefat code edit-menu-item-url\" name=\"menu-item-url[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->url); ?>\"/>\n </label>\n </p>\n <?php endif; ?>\n <p class=\"description description-thin\">\n <label for=\"edit-menu-item-title-<?php echo $item_id; ?>\">\n <?php _e('Navigation Label'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-title-<?php echo $item_id; ?>\"\n class=\"widefat edit-menu-item-title\" name=\"menu-item-title[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->title); ?>\"/>\n </label>\n </p>\n\n <p class=\"description description-thin\">\n <label for=\"edit-menu-item-attr-title-<?php echo $item_id; ?>\">\n <?php _e('Title Attribute'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-attr-title-<?php echo $item_id; ?>\"\n class=\"widefat edit-menu-item-attr-title\"\n name=\"menu-item-attr-title[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->post_excerpt); ?>\"/>\n </label>\n </p>\n\n <p class=\"field-link-target description\">\n <label for=\"edit-menu-item-target-<?php echo $item_id; ?>\">\n <input type=\"checkbox\" id=\"edit-menu-item-target-<?php echo $item_id; ?>\" value=\"_blank\"\n name=\"menu-item-target[<?php echo $item_id; ?>]\"<?php checked($item->target, '_blank'); ?> />\n <?php _e('Open link in a new window/tab'); ?>\n </label>\n </p>\n\n <p class=\"field-css-classes description description-thin\">\n <label for=\"edit-menu-item-classes-<?php echo $item_id; ?>\">\n <?php _e('CSS Classes (optional)'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-classes-<?php echo $item_id; ?>\"\n class=\"widefat code edit-menu-item-classes\" name=\"menu-item-classes[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr(implode(' ', $item->classes)); ?>\"/>\n </label>\n </p>\n\n <p class=\"field-xfn description description-thin\">\n <label for=\"edit-menu-item-xfn-<?php echo $item_id; ?>\">\n <?php _e('Link Relationship (XFN)'); ?><br/>\n <input type=\"text\" id=\"edit-menu-item-xfn-<?php echo $item_id; ?>\"\n class=\"widefat code edit-menu-item-xfn\" name=\"menu-item-xfn[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->xfn); ?>\"/>\n </label>\n </p>\n\n <p class=\"field-description description description-wide\">\n <label for=\"edit-menu-item-description-<?php echo $item_id; ?>\">\n <?php _e('Description'); ?><br/>\n <textarea id=\"edit-menu-item-description-<?php echo $item_id; ?>\"\n class=\"widefat edit-menu-item-description\" rows=\"3\" cols=\"20\"\n name=\"menu-item-description[<?php echo $item_id; ?>]\"><?php echo esc_html($item->description); // textarea_escaped\n ?></textarea>\n <span\n class=\"description\"><?php _e('The description will be displayed in the menu if the current theme supports it.'); ?></span>\n </label>\n </p>\n <?php\n /*\n * This is the added field\n */\n ?>\n <p class=\"field-custom description description-wide\">\n <label for=\"edit-menu-item-custom-<?php echo $item_id; ?>\">\n <?php _e('Checkbox'); ?><br/>\n <input type=\"checkbox\" id=\"edit-menu-item-custom-<?php echo $item_id; ?>\"\n class=\"widefat code edit-menu-item-custom\"\n name=\"menu-item-custom[<?php echo $item_id; ?>]\" <?php if ($item->custom == 'checked') {\n echo \"checked\";\n } ?> value=\"checked\"/>\n </label>\n </p>\n <?php\n /*\n * end added field\n */\n ?>\n <div class=\"menu-item-actions description-wide submitbox\">\n <?php if ('custom' != $item->type && $original_title !== false) : ?>\n <p class=\"link-to-original\">\n <?php printf(__('Original: %s'), '<a href=\"' . esc_attr($item->url) . '\">' . esc_html($original_title) . '</a>'); ?>\n </p>\n <?php endif; ?>\n <a class=\"item-delete submitdelete deletion\" id=\"delete-<?php echo $item_id; ?>\" href=\"<?php\n echo wp_nonce_url(\n add_query_arg(\n array(\n 'action' => 'delete-menu-item',\n 'menu-item' => $item_id,\n ),\n remove_query_arg($removed_args, admin_url('nav-menus.php'))\n ),\n 'delete-menu_item_' . $item_id\n ); ?>\"><?php _e('Remove'); ?></a> <span class=\"meta-sep\"> | </span> <a class=\"item-cancel submitcancel\"\n id=\"cancel-<?php echo $item_id; ?>\"\n href=\"<?php echo esc_url(add_query_arg(array('edit-menu-item' => $item_id, 'cancel' => time()), remove_query_arg($removed_args, admin_url('nav-menus.php'))));\n ?>#menu-item-settings-<?php echo $item_id; ?>\"><?php _e('Cancel'); ?></a>\n </div>\n\n <input class=\"menu-item-data-db-id\" type=\"hidden\" name=\"menu-item-db-id[<?php echo $item_id; ?>]\"\n value=\"<?php echo $item_id; ?>\"/>\n <input class=\"menu-item-data-object-id\" type=\"hidden\" name=\"menu-item-object-id[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->object_id); ?>\"/>\n <input class=\"menu-item-data-object\" type=\"hidden\" name=\"menu-item-object[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->object); ?>\"/>\n <input class=\"menu-item-data-parent-id\" type=\"hidden\" name=\"menu-item-parent-id[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->menu_item_parent); ?>\"/>\n <input class=\"menu-item-data-position\" type=\"hidden\" name=\"menu-item-position[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->menu_order); ?>\"/>\n <input class=\"menu-item-data-type\" type=\"hidden\" name=\"menu-item-type[<?php echo $item_id; ?>]\"\n value=\"<?php echo esc_attr($item->type); ?>\"/>\n </div>\n <!-- .menu-item-settings-->\n <ul class=\"menu-item-transport\"></ul>\n <?php\n $output .= ob_get_clean();\n }\n}\n/**\n* The same as the one on top but with a different fiel\n*/\nclass BackendFooter extends Walker_Nav_Menu_Edit\n{\n\n /*\n * This is the added field\n */\n ?>\n <p class=\"field-icon description description-wide\">\n <label for=\"edit-menu-item-icon-<?php echo $item_id; ?>\">\n <?php _e('Icon'); ?><br/>\n <select id=\"edit-menu-item-icon-<?php echo $item_id; ?>\" class=\"widefat code edit-menu-item-icon\" name=\"menu-item-icon[<?php echo $item_id; ?>]\">\n <option <?php if('icon' == $item->icon) { echo \"selected='selected'\"; } ?> value=\"icon\">Icon One</option>\n<option <?php if('icon2' == $item->icon) { echo \"selected='selected'\"; } ?> value=\"icon2\">Icon Two</option>\n<option <?php if('icon3' == $item->icon) { echo \"selected='selected'\"; } ?> value=\"icon3\">Icon Three</option>\n <?php } ?>\n </select>\n </label>\n </p>\n <?php\n /*\n * end added field\n */\n ?>\n\n}\n</code></pre>\n"
},
{
"answer_id": 331910,
"author": "anastymous",
"author_id": 51205,
"author_profile": "https://wordpress.stackexchange.com/users/51205",
"pm_score": 1,
"selected": false,
"text": "<p>You'll find it much easier to control which fields are shown, by controlling which walker is used. Rather than trying to 'toggle' the fields inside the walker.</p>\n\n<p>I also wanted to show a bunch of custom fields, and only show them on a menu at a particular menu location. So I used the following...</p>\n\n<pre><code>add_filter( 'wp_edit_nav_menu_walker', function( $walker, $menu_id ) {\n\n $menu_locations = get_nav_menu_locations();\n\n if ( $menu_locations['main_menu'] == $menu_id ) {\n return 'Walker_Nav_Menu_Custom';\n } else {\n return $walker;\n }\n\n}, 10, 2); \n</code></pre>\n"
},
{
"answer_id": 398523,
"author": "Jake",
"author_id": 64348,
"author_profile": "https://wordpress.stackexchange.com/users/64348",
"pm_score": 0,
"selected": false,
"text": "<p>Simply transposing the array returned by <code>get_nav_menu_locations()</code> gives you a mapping from menu ID to menu location:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$menu_locations = \\array_flip(\\get_nav_menu_locations());\n$menu_location = $menu_locations[$menu_id] ?? null; \nif ($menu_location === 'main_nav') {\n do_something();\n}\n</code></pre>\n<p>This above code includes getting the menu location of a specific menu by ID.</p>\n<p>If you don't have a menu ID but instead have the name or slug, you can use <code>wp_get_nav_menu_object()</code> first to get the ID:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$menu_term = \\wp_get_nav_menu_object($menu_slug_name_id_or_wpterm);\n$menu_id = \\is_object($menu_term) ? $menu_term->term_id : null;\n</code></pre>\n<p>Then continue with the code above to get the location from the ID.</p>\n<p>(<code>wp_get_nav_menu_object()</code> will also accept an ID or <code>WP_Term</code>, so you can throw whatever you have at it to get a <code>WP_Term</code> to get the ID.)</p>\n"
}
] |
2015/06/24
|
[
"https://wordpress.stackexchange.com/questions/192513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75173/"
] |
I'm looking for some help in creating a query based on fields I made in Advanced Custom Fields. I'd like to create a query that would loop through a custom post type, using arguments such as:
```
?genre=Dance&keyword=&mood=&album=
```
What I expect from this query is all posts with the `genre` meta-field of "Dance" to be posted. Since all of the other arguments have no value, I'm expecting these to be ignored in the query. If the arguments change to:
```
?genre=Dance&keyword=&mood=happy&album=
```
I want the query to narrow down and only find posts with the `genre` meta-field of "Dance" and the `mood` meta-field of "Happy".
Here's the code I'm using that gives me some of the results. The only way to add my mood variable to the query is if I use 'AND' as the relation and add it as another array, but then I lose being able to just query using one argument.
```
$queryGenre = $_GET['genre'];
$paged = get_query_var( 'paged' );
$loop = new WP_Query( array(
'posts_per_page' => 5,
'post_type' => 'catalog',
'paged' => $paged,
'order_by' => 'ASC',
'meta_query' => array(
array(
'key' => 'genre',
'value' => $queryGenre,
'compare' => '=',
)
)
) );
while ( $loop->have_posts() ) : $loop->the_post();
```
|
You'll find it much easier to control which fields are shown, by controlling which walker is used. Rather than trying to 'toggle' the fields inside the walker.
I also wanted to show a bunch of custom fields, and only show them on a menu at a particular menu location. So I used the following...
```
add_filter( 'wp_edit_nav_menu_walker', function( $walker, $menu_id ) {
$menu_locations = get_nav_menu_locations();
if ( $menu_locations['main_menu'] == $menu_id ) {
return 'Walker_Nav_Menu_Custom';
} else {
return $walker;
}
}, 10, 2);
```
|
192,555 |
<p>I want my media-library and all currently uploaded files distributed and available to all users. I am using the <a href="https://wordpress.org/plugins/user-role-editor/" rel="nofollow">User Role Editor Plugin</a></p>
<p>Is there any functions.php hack that makes all media-uploads visible to all users and roles?</p>
<p>I have a subscriber that is possible to edit a few pages and upload media, but the media uploads that are currently in the library for admins are not visible to the subscriber.</p>
<p>Update: My current approach, that is not working so far.</p>
<p>my functions.php file: </p>
<pre><code>add_action( 'admin_init', 'rk_shared_uploads' );
add_action( 'init', 'rk_shared_uploads');
function rk_shared_uploads() {
$subscriber = get_role( 'subscriber' );
$subscriber->add_cap( 'upload_files' );
$subscriber->add_cap( 'unfiltered_upload' );
$contributor = get_role( 'contributor' );
$contributor->add_cap( 'upload_files' );
$contributor->add_cap( 'unfiltered_upload' );
$author = get_role( 'author' );
$author->add_cap( 'upload_files' );
$author->add_cap( 'unfiltered_upload' );
}
</code></pre>
<p>in my wp-config.php</p>
<pre><code>const PP_MEDIA_LIB_UNFILTERED = true;
</code></pre>
|
[
{
"answer_id": 192784,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": -1,
"selected": false,
"text": "<p>I have not tested but the following code will help you please add the following two lines of code to your function.php file</p>\n\n<pre><code>$role= get_role([role_name ]);\n$role->add_cap('upload_files');\n</code></pre>\n"
},
{
"answer_id": 192788,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>The plugin you mentioned is only reportedly tested up to WordPress version 3.6.1.</p>\n\n<p>I would not (in general) recommend abandoned plugins, because they might impose security risks.</p>\n\n<p>Additionally it uses PHP4 class constructors, that might soon be deprecated and it calls non static methods in a static way.</p>\n\n<p>If you remove the plugin, you should be able to use your code snippet:</p>\n\n<pre><code>add_action( 'admin_init', 'mathiregister_allow_uploads' );\n\nfunction mathiregister_allow_uploads() {\n $contributor = get_role( 'contributor' );\n $contributor->add_cap('upload_files');\n}\n</code></pre>\n\n<p>to allow <code>contributors</code> to get access to the media library and upload files. </p>\n\n<p><em>Remember to prefix your filter callbacks, to avoid name collisions</em>.</p>\n\n<p>ps: Skimming through the plugin code, you might be able to bypass the plugin's media restrictions by defining:</p>\n\n<pre><code>define( 'SCOPER_ALL_UPLOADS_EDITABLE ', true );\n</code></pre>\n\n<p>or do it <a href=\"https://wordpress.stackexchange.com/a/191560/26350\">@toscho style</a>:</p>\n\n<pre><code>const SCOPER_ALL_UPLOADS_EDITABLE = true;\n</code></pre>\n\n<p>in the global scope, for example in your <code>wp-config.php</code> file.</p>\n\n<p>But you should really consider using up-to-date plugins.</p>\n"
},
{
"answer_id": 192830,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried adding the <code>unfiltered_upload</code> capability too?</p>\n\n<pre><code>function add_theme_caps() {\n // gets the author role\n $role = get_role( 'subscriber' );\n\n $role->add_cap( 'upload_files' ); \n $role->add_cap( 'unfiltered_upload' );\n}\n\nadd_action( 'admin_init', 'add_theme_caps');\nadd_action( 'init', 'add_theme_caps');\n</code></pre>\n"
}
] |
2015/06/25
|
[
"https://wordpress.stackexchange.com/questions/192555",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3529/"
] |
I want my media-library and all currently uploaded files distributed and available to all users. I am using the [User Role Editor Plugin](https://wordpress.org/plugins/user-role-editor/)
Is there any functions.php hack that makes all media-uploads visible to all users and roles?
I have a subscriber that is possible to edit a few pages and upload media, but the media uploads that are currently in the library for admins are not visible to the subscriber.
Update: My current approach, that is not working so far.
my functions.php file:
```
add_action( 'admin_init', 'rk_shared_uploads' );
add_action( 'init', 'rk_shared_uploads');
function rk_shared_uploads() {
$subscriber = get_role( 'subscriber' );
$subscriber->add_cap( 'upload_files' );
$subscriber->add_cap( 'unfiltered_upload' );
$contributor = get_role( 'contributor' );
$contributor->add_cap( 'upload_files' );
$contributor->add_cap( 'unfiltered_upload' );
$author = get_role( 'author' );
$author->add_cap( 'upload_files' );
$author->add_cap( 'unfiltered_upload' );
}
```
in my wp-config.php
```
const PP_MEDIA_LIB_UNFILTERED = true;
```
|
The plugin you mentioned is only reportedly tested up to WordPress version 3.6.1.
I would not (in general) recommend abandoned plugins, because they might impose security risks.
Additionally it uses PHP4 class constructors, that might soon be deprecated and it calls non static methods in a static way.
If you remove the plugin, you should be able to use your code snippet:
```
add_action( 'admin_init', 'mathiregister_allow_uploads' );
function mathiregister_allow_uploads() {
$contributor = get_role( 'contributor' );
$contributor->add_cap('upload_files');
}
```
to allow `contributors` to get access to the media library and upload files.
*Remember to prefix your filter callbacks, to avoid name collisions*.
ps: Skimming through the plugin code, you might be able to bypass the plugin's media restrictions by defining:
```
define( 'SCOPER_ALL_UPLOADS_EDITABLE ', true );
```
or do it [@toscho style](https://wordpress.stackexchange.com/a/191560/26350):
```
const SCOPER_ALL_UPLOADS_EDITABLE = true;
```
in the global scope, for example in your `wp-config.php` file.
But you should really consider using up-to-date plugins.
|
192,597 |
<p>In my WordPress project, I have several different <code>custom post types</code> and they all share a <strong>common</strong> taxonomy. I am in the final stage of the project and now is time to link all custom post types using a sidebar widget. The problem I am having is that I don't know the appropriate way to get the <code>term link</code> linked to the correct custom post type.</p>
<p>For example, I have custom post types: book, author, product; and a taxonomy: genre that includes a horror category.</p>
<p>I would like to be able to get link structure as such:</p>
<pre><code>/book/genre/horror
/product/genre/horror
/author/genre/horror
</code></pre>
<p>When I do <code>get_term_link('horror');</code>, I get one of the term links, it seems that one of the custom post type has preference. How can I manage to get each term link corresponding to the correct custom post type?</p>
<p>Hard coding it is never a good idea, so I was wondering if there is a proper way to go about this. This is an old issue I am having, and have done a lot of searching for a solution but I didn't find it. I come here as the last resort. Thanks.</p>
|
[
{
"answer_id": 193758,
"author": "Caio Mar",
"author_id": 54189,
"author_profile": "https://wordpress.stackexchange.com/users/54189",
"pm_score": 0,
"selected": false,
"text": "<p>Good news, I figured out a way to accomplish this. Here is my solution.</p>\n\n<p>Taking my example above, I will walk you through what I did to get <code>example.com/book/genre/horror</code> to point to custom post type <code>book</code>, taxonomy <code>genre</code> and category <code>horror</code>.</p>\n\n<p>Pretty permalinks should be enabled. Go to Settings > Permalinks to enable it. Otherwise there is no point of doing this. So here we go...</p>\n\n<p>1) Create a page called book (and slug book), note the page ID that was generated for that page after you have published it, you will need it ( you can see this in your URL, should be a <code>?post=</code> with the page ID in it.)</p>\n\n<p>2) Now we need to create a rewrite so that we can point the link to the correct template page. So, in your <code>functions.php</code> file (or your plugin file, up to you) you need to add this code:</p>\n\n<pre><code>function my_rewrite_rules() {\n\n add_rewrite_rule(\n 'book/genre/([[A-Za-z0-9\\-]+)?/?$',\n 'index.php?page_id=1234&genre=$matches[1]',\n 'top'\n );\n\n flush_rewrite_rules();\n}\nadd_action( 'init', 'my_rewrite_rules' );\n</code></pre>\n\n<p>Now, replace 1234 with the page ID you generated for the page <code>book</code>. And go to any front end page and reload it.</p>\n\n<p><strong>Important:</strong> you don't want to run <code>flush_rewrite_rules();</code> every time a page is loaded in your site. This is a heavy function and will slow things down for you. You only need to run it once on the <strong>front end</strong>. After you reloaded any page on the front end, the rewrite rules are flushed and you can remove this line.</p>\n\n<p>What this function does is, if a url is has the structure of <code>/book/genre/ANYTHING_HERE/</code>, WordPress will redirect user to the page with ID of 1234 with the data <code>genre=ANYTHING_HERE</code>. Note that ANYTHING_HERE is filtered through the regular expression provided, and that will only accept characters (upper-case and lower-case) from a-z, numbers 0-9 and dash (-).</p>\n\n<p>3) Go to your theme folder and create a file called <code>page-1234.php</code> (replacing 1234 with <strong>your</strong> page ID, of course.) Now in this file you can do all sorts of fun stuff. Here is how you could list all books <strong>by genre</strong>:</p>\n\n<pre><code><?php\nget_header(); \n\nglobal $wp_query;\n$genre = $wp_query->query_vars['genre'];\n\n$args = array(\n 'post_type' => 'book',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'genre',\n 'field' => 'slug',\n 'terms' => $genre,\n ), ),\n);\n\n$books = new WP_Query( $args );\n?>\n\n<h1>Books of <?php echo $genre;?></h1>\n<ul>\n<?php foreach ( $books as $book ) : ?>\n <li><?php echo $book->post_title; ?></li>\n<?php endforeach; ?>\n</ul>\n\n<?php get_footer(); ?>\n</code></pre>\n\n<p>In addition, if you are not working with taxonomies, like <code>genre</code> in this example, you could use your custom tags. By the way, the term <code>genre</code> only works in this example because it was registered as a taxonomy. If this wasn't the case, you could add a new tag to WordPress, whatever you would like, by adding this to your <code>functions.php</code> as such:</p>\n\n<pre><code>function custom_rewrite_tag() {\n add_rewrite_tag('%food%', '([^&]+)');\n}\nadd_action('init', 'custom_rewrite_tag', 10, 0);\n</code></pre>\n\n<p>Now you replace <code>genre</code> in the step 2 with the tag <code>food</code>. In your <code>page-1234.php</code> you can get the <code>query_vars['food']</code> and manipulate it any way you like and run requests like <code>example.com/book/food/chocolate</code>. Note that some query_vars are reserved. Check the resources below for them.</p>\n\n<p>To finish off, to get the links to point to the correct custom post type and taxonomy, you need a custom function. This is the only way I could think of doing this and it is something like this:</p>\n\n<pre><code>function get_books_category_link( $category_slug ) {\n\n $page = get_permalink( 1234 );\n $link = '';\n\n if ( '/%postname%/' == get_option('permalink_structure') ) {\n $link = $page . 'genre/' . $category_slug;\n } else {\n $link = add_query_arg( array( 'genre' => $category_slug ) , $page );\n }\n\n return $link;\n}\n</code></pre>\n\n<p>And that's it! Hope it helps. Some great reads below, specially the article from Stephen Harris really made a difference on understanding the rewrite API. Thanks.</p>\n\n<p><a href=\"http://code.tutsplus.com/articles/the-rewrite-api-the-basics--wp-25474\" rel=\"nofollow\">Tuts+ The Rewrite API: The Basics</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\">Rewrite API/add rewrite rule</a></p>\n\n<p><a href=\"https://codex.wordpress.org/WordPress_Query_Vars\" rel=\"nofollow\">WordPress Query Vars</a></p>\n"
},
{
"answer_id": 193809,
"author": "Kd dev",
"author_id": 74021,
"author_profile": "https://wordpress.stackexchange.com/users/74021",
"pm_score": 1,
"selected": false,
"text": "<p>This code display all posts of all categories of <strong>genre taxonomy</strong> for <strong>custom post type book</strong>. Now, For different <strong>custom post type (author, product ) you have to change Custom Post Type Name inside $arg of WP_Query().</strong> You will get term link using get_term_link($catterm) function or you can use also <a href=\"http://codex.wordpress.org/Function_Reference/get_the_term_list\" rel=\"nofollow\">get_the_term_list()</a>.</p>\n\n<pre><code> $args = array(\n 'number' => $number,\n 'hide_empty' => $hide_empty,\n 'include' => $ids\n );\n\n $custom_categories = get_terms( 'genre ', $args );\n\n foreach ( $custom_categories as $catterm){\n\n $arg = Array( \n 'post_type' => 'book',\n 'posts_per_page' => '-1',\n 'post_status' => 'publish',\n 'tax_query' => Array( Array ( \n 'taxonomy' => 'genre ' ,\n 'terms' => $catterm->term_id\n )) );\n\n $loop = new WP_Query( $arg ); \n global $post;\n while ( $loop->have_posts() ) : $loop->the_post();\n ?>\n\n <div class=\"gallery-content\">\n <div class=\"entry-content\">\n\n <?php \n echo '<li>' . get_the_title() . '</li>';\n echo '<li><a href=\"'.get_term_link($catterm).'\">'.$catterm->name.'</a></li>'; \n ?> \n\n </div>\n </div>\n\n <?php endwhile;\n } \n ?>\n</code></pre>\n"
}
] |
2015/06/25
|
[
"https://wordpress.stackexchange.com/questions/192597",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54189/"
] |
In my WordPress project, I have several different `custom post types` and they all share a **common** taxonomy. I am in the final stage of the project and now is time to link all custom post types using a sidebar widget. The problem I am having is that I don't know the appropriate way to get the `term link` linked to the correct custom post type.
For example, I have custom post types: book, author, product; and a taxonomy: genre that includes a horror category.
I would like to be able to get link structure as such:
```
/book/genre/horror
/product/genre/horror
/author/genre/horror
```
When I do `get_term_link('horror');`, I get one of the term links, it seems that one of the custom post type has preference. How can I manage to get each term link corresponding to the correct custom post type?
Hard coding it is never a good idea, so I was wondering if there is a proper way to go about this. This is an old issue I am having, and have done a lot of searching for a solution but I didn't find it. I come here as the last resort. Thanks.
|
This code display all posts of all categories of **genre taxonomy** for **custom post type book**. Now, For different **custom post type (author, product ) you have to change Custom Post Type Name inside $arg of WP\_Query().** You will get term link using get\_term\_link($catterm) function or you can use also [get\_the\_term\_list()](http://codex.wordpress.org/Function_Reference/get_the_term_list).
```
$args = array(
'number' => $number,
'hide_empty' => $hide_empty,
'include' => $ids
);
$custom_categories = get_terms( 'genre ', $args );
foreach ( $custom_categories as $catterm){
$arg = Array(
'post_type' => 'book',
'posts_per_page' => '-1',
'post_status' => 'publish',
'tax_query' => Array( Array (
'taxonomy' => 'genre ' ,
'terms' => $catterm->term_id
)) );
$loop = new WP_Query( $arg );
global $post;
while ( $loop->have_posts() ) : $loop->the_post();
?>
<div class="gallery-content">
<div class="entry-content">
<?php
echo '<li>' . get_the_title() . '</li>';
echo '<li><a href="'.get_term_link($catterm).'">'.$catterm->name.'</a></li>';
?>
</div>
</div>
<?php endwhile;
}
?>
```
|
192,608 |
<p>I have restricted a users capabilities</p>
<pre><code>$capabilities = array(
'delete_posts' => true,
'delete_published_posts' => true,
'edit_posts' => true,
'edit_published_posts' => true,
'publish_posts' => true,
'read' => true,
'upload_files' => true
);
</code></pre>
<p>Everything works as I expect, except that the user cannot insert images into the editor field in a CPT, despite the fact they have the <code>upload files</code> capability.</p>
<pre><code>'supports' => array( 'title', 'editor' ),
</code></pre>
<p>What capability have I missed that lets them do this?</p>
<p><strong>EDIT</strong></p>
<p>So the offending code is somewhere below</p>
<pre><code>function remove_admin_menu_items() {
if ( current_user_can( 'test_author' ) ) {
/** remove side dashboard items */
remove_menu_page( 'edit.php' ); //Posts
remove_menu_page( 'edit.php?post_type=page' ); //Pages
remove_menu_page( 'edit-comments.php' ); //Comments
remove_menu_page( 'themes.php' ); //Appearance
remove_menu_page( 'plugins.php' ); //Plugins
remove_menu_page( 'users.php' ); //Users
remove_menu_page( 'tools.php' ); //Tools
remove_menu_page( 'options-general.php' ); //Settings
remove_menu_page( 'edit.php?post_type=cpt_customposttype' );
}
}
add_action( 'admin_init', 'remove_admin_menu_items' ); //use late hook so plugins have all loaded
</code></pre>
|
[
{
"answer_id": 192610,
"author": "sakibmoon",
"author_id": 23214,
"author_profile": "https://wordpress.stackexchange.com/users/23214",
"pm_score": 1,
"selected": false,
"text": "<p>You haven't missed any capabilities. User should be able to insert images into the editor with these capabilities.</p>\n<p>The only problem I can think of is that, you are trying to modify the capabilities of a role which won't work.</p>\n<p><a href=\"https://codex.wordpress.org/Function_Reference/add_role#Delete_existing_role\" rel=\"nofollow noreferrer\">See this section</a></p>\n<blockquote>\n<p>If you are defining a custom role, and adding capabilities to the role using add_role(), be aware that modifying the capabilities array and re-executing add_role() will not necessarily update the role with the new capabilities list. The add_role() function short-circuits if the role already exists in the database.</p>\n<p>The workaround in this case is to precede your add_role() call with a remove_role() call that targets the role you are adding.</p>\n</blockquote>\n"
},
{
"answer_id": 192717,
"author": "myol",
"author_id": 51823,
"author_profile": "https://wordpress.stackexchange.com/users/51823",
"pm_score": 0,
"selected": false,
"text": "<p>I found the issue. Somewhere online recommended to use a late hook so all the plugins loaded. </p>\n\n<pre><code>add_action( 'admin_init', 'remove_admin_menu_items' );\n</code></pre>\n\n<p>Obviously I used the wrong hook. Instead I used the codex recommendation</p>\n\n<pre><code>add_action( 'admin_menu', 'remove_admin_menu_items' );\n</code></pre>\n"
}
] |
2015/06/25
|
[
"https://wordpress.stackexchange.com/questions/192608",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51823/"
] |
I have restricted a users capabilities
```
$capabilities = array(
'delete_posts' => true,
'delete_published_posts' => true,
'edit_posts' => true,
'edit_published_posts' => true,
'publish_posts' => true,
'read' => true,
'upload_files' => true
);
```
Everything works as I expect, except that the user cannot insert images into the editor field in a CPT, despite the fact they have the `upload files` capability.
```
'supports' => array( 'title', 'editor' ),
```
What capability have I missed that lets them do this?
**EDIT**
So the offending code is somewhere below
```
function remove_admin_menu_items() {
if ( current_user_can( 'test_author' ) ) {
/** remove side dashboard items */
remove_menu_page( 'edit.php' ); //Posts
remove_menu_page( 'edit.php?post_type=page' ); //Pages
remove_menu_page( 'edit-comments.php' ); //Comments
remove_menu_page( 'themes.php' ); //Appearance
remove_menu_page( 'plugins.php' ); //Plugins
remove_menu_page( 'users.php' ); //Users
remove_menu_page( 'tools.php' ); //Tools
remove_menu_page( 'options-general.php' ); //Settings
remove_menu_page( 'edit.php?post_type=cpt_customposttype' );
}
}
add_action( 'admin_init', 'remove_admin_menu_items' ); //use late hook so plugins have all loaded
```
|
You haven't missed any capabilities. User should be able to insert images into the editor with these capabilities.
The only problem I can think of is that, you are trying to modify the capabilities of a role which won't work.
[See this section](https://codex.wordpress.org/Function_Reference/add_role#Delete_existing_role)
>
> If you are defining a custom role, and adding capabilities to the role using add\_role(), be aware that modifying the capabilities array and re-executing add\_role() will not necessarily update the role with the new capabilities list. The add\_role() function short-circuits if the role already exists in the database.
>
>
> The workaround in this case is to precede your add\_role() call with a remove\_role() call that targets the role you are adding.
>
>
>
|
192,619 |
<p>I am using wp_localize_script to pass values to a jquery script. Sometimes this might happen several times on the same page, which means I need to set a different variable name to each wp_localize_script. That also means that my jquery script doesn't know what is the variable name being passed by wp_localize_script because the variable name is dynamically created (incremented).</p>
<p>So right now my solution is to add the same variable name (being passed by wp_localize_script) to a data attribute in the html tag, and then select all those attributes using a common class.</p>
<p>Example:</p>
<p>In my page I have the variable name that's going to be passed to the script dynamically generated (incremented) so that I can call wp_localize_script several times without overriding the values.</p>
<pre><code>//PHP
$my_var = array('test_var'=>"yes");
wp_localize_script('my_script_handle','my_var_1',$my_var);
//Later down the page...
$my_var = array('test_var'=>"no");
wp_localize_script('my_script_handle','my_var_2',$my_var);
</code></pre>
<p>I also add the same variable name to a html data attribute</p>
<pre><code><div class="get_this" data-var="my_var_1">Some content</div>
<div class="get_this" data-var="my_var_2">Some more content</div>
</code></pre>
<p>Then in JS I use this selector:</p>
<pre><code>var my_vars = $(".get_this").data("var");
my_vars.each(function()){
alert(my_vars.test_var);
}
</code></pre>
<p><strong>Is there a better approach to this?</strong>
This works, but seems redundant to use wp_localize_script to send some variables over to the js script, and then have to rely on a class or data element to get all instances.</p>
|
[
{
"answer_id": 192610,
"author": "sakibmoon",
"author_id": 23214,
"author_profile": "https://wordpress.stackexchange.com/users/23214",
"pm_score": 1,
"selected": false,
"text": "<p>You haven't missed any capabilities. User should be able to insert images into the editor with these capabilities.</p>\n<p>The only problem I can think of is that, you are trying to modify the capabilities of a role which won't work.</p>\n<p><a href=\"https://codex.wordpress.org/Function_Reference/add_role#Delete_existing_role\" rel=\"nofollow noreferrer\">See this section</a></p>\n<blockquote>\n<p>If you are defining a custom role, and adding capabilities to the role using add_role(), be aware that modifying the capabilities array and re-executing add_role() will not necessarily update the role with the new capabilities list. The add_role() function short-circuits if the role already exists in the database.</p>\n<p>The workaround in this case is to precede your add_role() call with a remove_role() call that targets the role you are adding.</p>\n</blockquote>\n"
},
{
"answer_id": 192717,
"author": "myol",
"author_id": 51823,
"author_profile": "https://wordpress.stackexchange.com/users/51823",
"pm_score": 0,
"selected": false,
"text": "<p>I found the issue. Somewhere online recommended to use a late hook so all the plugins loaded. </p>\n\n<pre><code>add_action( 'admin_init', 'remove_admin_menu_items' );\n</code></pre>\n\n<p>Obviously I used the wrong hook. Instead I used the codex recommendation</p>\n\n<pre><code>add_action( 'admin_menu', 'remove_admin_menu_items' );\n</code></pre>\n"
}
] |
2015/06/25
|
[
"https://wordpress.stackexchange.com/questions/192619",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30984/"
] |
I am using wp\_localize\_script to pass values to a jquery script. Sometimes this might happen several times on the same page, which means I need to set a different variable name to each wp\_localize\_script. That also means that my jquery script doesn't know what is the variable name being passed by wp\_localize\_script because the variable name is dynamically created (incremented).
So right now my solution is to add the same variable name (being passed by wp\_localize\_script) to a data attribute in the html tag, and then select all those attributes using a common class.
Example:
In my page I have the variable name that's going to be passed to the script dynamically generated (incremented) so that I can call wp\_localize\_script several times without overriding the values.
```
//PHP
$my_var = array('test_var'=>"yes");
wp_localize_script('my_script_handle','my_var_1',$my_var);
//Later down the page...
$my_var = array('test_var'=>"no");
wp_localize_script('my_script_handle','my_var_2',$my_var);
```
I also add the same variable name to a html data attribute
```
<div class="get_this" data-var="my_var_1">Some content</div>
<div class="get_this" data-var="my_var_2">Some more content</div>
```
Then in JS I use this selector:
```
var my_vars = $(".get_this").data("var");
my_vars.each(function()){
alert(my_vars.test_var);
}
```
**Is there a better approach to this?**
This works, but seems redundant to use wp\_localize\_script to send some variables over to the js script, and then have to rely on a class or data element to get all instances.
|
You haven't missed any capabilities. User should be able to insert images into the editor with these capabilities.
The only problem I can think of is that, you are trying to modify the capabilities of a role which won't work.
[See this section](https://codex.wordpress.org/Function_Reference/add_role#Delete_existing_role)
>
> If you are defining a custom role, and adding capabilities to the role using add\_role(), be aware that modifying the capabilities array and re-executing add\_role() will not necessarily update the role with the new capabilities list. The add\_role() function short-circuits if the role already exists in the database.
>
>
> The workaround in this case is to precede your add\_role() call with a remove\_role() call that targets the role you are adding.
>
>
>
|
192,624 |
<p>I'm trying to mock <code>get_adjacent_post</code> for unit testing but I'm not sure how to mock global function in PHPUnit</p>
<pre><code> $badCode = $this->getMockBuilder('get_adjacent_post')
->setMethods(array('somthing'))
->getMock();
</code></pre>
<p>Here's what I got so far which obviously doesn't work. </p>
<p>And here's how I use it in production code.</p>
<pre><code>$prev_post = get_adjacent_post( true, '', true, 'topic' );
</code></pre>
|
[
{
"answer_id": 192701,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 2,
"selected": false,
"text": "<p>I think you are looking for <a href=\"https://github.com/10up/wp_mock\" rel=\"nofollow\">WP_Mock</a>:</p>\n\n<blockquote>\n <p>WP_Mock is an API mocking framework, built and maintained by 10up for the purpose of making it possible to properly unit test within WordPress.</p>\n</blockquote>\n\n<p>From <a href=\"https://github.com/10up/wp_mock#using-wp_mock\" rel=\"nofollow\">an example there</a>, you'd mock <code>get_permalink()</code> like this:</p>\n\n<pre><code> \\WP_Mock::wpFunction( 'get_permalink', array(\n 'args' => 42,\n 'times' => 1,\n 'return' => 'http://example.com/foo'\n ) );\n</code></pre>\n"
},
{
"answer_id": 192736,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<p>I used <code>WP_Mock</code> for a long time, until I built <a href=\"http://giuseppe-mazzapica.github.io/BrainMonkey/\" rel=\"nofollow\">Brain Monkey</a> to overcome some problems I found working with it.</p>\n\n<p>Using <em>Brain Monkey</em> you can:</p>\n\n<pre><code>use Brain\\Monkey\\Functions;\n\nFunctions::when('get_adjacent_post')->alias(function() {\n // mock here...\n});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Functions::expect('get_adjacent_post')\n ->atLeast()\n ->once()\n ->with( true, '', true, 'topic' )\n ->andReturnUsing(function( $in_same_term, $excluded_terms, $previous ) {\n // mock here\n });\n</code></pre>\n\n<p>This latter syntax comes from <a href=\"https://github.com/padraic/mockery\" rel=\"nofollow\">Mockery</a>.</p>\n\n<p><em>Brain Monkey</em>, just like <em>WP_Mock</em>, has an API to also mock WordPress hooks.</p>\n"
}
] |
2015/06/25
|
[
"https://wordpress.stackexchange.com/questions/192624",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62360/"
] |
I'm trying to mock `get_adjacent_post` for unit testing but I'm not sure how to mock global function in PHPUnit
```
$badCode = $this->getMockBuilder('get_adjacent_post')
->setMethods(array('somthing'))
->getMock();
```
Here's what I got so far which obviously doesn't work.
And here's how I use it in production code.
```
$prev_post = get_adjacent_post( true, '', true, 'topic' );
```
|
I think you are looking for [WP\_Mock](https://github.com/10up/wp_mock):
>
> WP\_Mock is an API mocking framework, built and maintained by 10up for the purpose of making it possible to properly unit test within WordPress.
>
>
>
From [an example there](https://github.com/10up/wp_mock#using-wp_mock), you'd mock `get_permalink()` like this:
```
\WP_Mock::wpFunction( 'get_permalink', array(
'args' => 42,
'times' => 1,
'return' => 'http://example.com/foo'
) );
```
|
192,708 |
<p>I am working on a site where I use get_template_part to retrieve the loop. In the header of the template I specified so it runs the global query. </p>
<pre><code>global $user_ID, $wp_query, $pagename;
</code></pre>
<p>Now, what does best practice say if I want multiple queries on the same page? I tried to simply go in and specify another global variable <strong>e.g. $wp_query2</strong> in the header, but I somewhere read that using global variables for this is actually bad practice. </p>
<p>Unfortunately, <em>I cannot rely on slugs for the loop</em> or I would use that. It's the frontpage. I was thinking about <strong>passing a variable via "get_template_part"</strong> but that is not supported? </p>
<p>Never had to do this, so what would you use? </p>
|
[
{
"answer_id": 249416,
"author": "Jackie Taferner",
"author_id": 109052,
"author_profile": "https://wordpress.stackexchange.com/users/109052",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone stumbling across this post with the same problem, I was able to resolve it by removing the <code>/wp-content/mu-plugins/</code> directory. This seems to be a leftover Godaddy \"helper\" which my client previously used to install their website.</p>\n"
},
{
"answer_id": 353062,
"author": "ott",
"author_id": 117421,
"author_profile": "https://wordpress.stackexchange.com/users/117421",
"pm_score": 1,
"selected": false,
"text": "<p>Did you migrate from managed wp to unmanaged? Check this page\n<a href=\"https://ru.godaddy.com/help/move-a-managed-wordpress-site-to-an-unmanaged-wordpress-account-19798\" rel=\"nofollow noreferrer\">https://ru.godaddy.com/help/move-a-managed-wordpress-site-to-an-unmanaged-wordpress-account-19798</a></p>\n\n<p>In the site directory, locate the /wp-content/mu-plugins/ directory, and delete the gd-system-plugin and gd-system-plugin.php files.</p>\n\n<p>In the wp-config.php file, find and remove the reference to gd-config.php. The sample code below from the wp-config.php file shows the general location of the line to delete.</p>\n"
}
] |
2015/06/26
|
[
"https://wordpress.stackexchange.com/questions/192708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7820/"
] |
I am working on a site where I use get\_template\_part to retrieve the loop. In the header of the template I specified so it runs the global query.
```
global $user_ID, $wp_query, $pagename;
```
Now, what does best practice say if I want multiple queries on the same page? I tried to simply go in and specify another global variable **e.g. $wp\_query2** in the header, but I somewhere read that using global variables for this is actually bad practice.
Unfortunately, *I cannot rely on slugs for the loop* or I would use that. It's the frontpage. I was thinking about **passing a variable via "get\_template\_part"** but that is not supported?
Never had to do this, so what would you use?
|
Did you migrate from managed wp to unmanaged? Check this page
<https://ru.godaddy.com/help/move-a-managed-wordpress-site-to-an-unmanaged-wordpress-account-19798>
In the site directory, locate the /wp-content/mu-plugins/ directory, and delete the gd-system-plugin and gd-system-plugin.php files.
In the wp-config.php file, find and remove the reference to gd-config.php. The sample code below from the wp-config.php file shows the general location of the line to delete.
|
192,733 |
<p>I'm using Advanced Custom Fields and Content Protector plugins in trying to protect an iframe for eventbrite ticket registration that gets displayed through Event Calendar plugin. I believe I'm wrapping the part that displayed the iframe with the Content Protector shortcode, but it gets displayed anyway even before entering the password. How could I make it so the iframe is displayed only when the password is entered?</p>
<pre><code><?php
$password = get_post_custom_values('password');
if(!empty($password)){
echo do_shortcode("[content_protector password=". "'".$password[0]."']". do_action( 'tribe_events_single_event_after_the_meta' ). "[/content_protector]");
} else {
do_action( 'tribe_events_single_event_after_the_meta' );
}
?>
</code></pre>
|
[
{
"answer_id": 192734,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 2,
"selected": false,
"text": "<p><code>do_action</code> does not return text, it just does the action. So, calling <code>do_action( 'tribe_events_single_event_after_the_meta' )</code> in your <code>do_shortcode</code> call there will cause the iframe to be output before the shortcode.</p>\n"
},
{
"answer_id": 192934,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "<p>Following on from @Otto, you need to <em>capture</em> the output from the action, and then pass it through the shortcode:</p>\n\n<pre><code>ob_start();\ndo_action( 'tribe_events_single_event_after_the_meta' );\n$calendar = ob_get_clean();\n\n$password = get_post_custom_values( 'password' );\n\nif( ! empty( $password ) ) {\n echo do_shortcode( \"[content_protector password='{$password[0]}']{$calendar}[/content_protector]\" );\n} else {\n echo $calendar;\n}\n</code></pre>\n"
}
] |
2015/06/26
|
[
"https://wordpress.stackexchange.com/questions/192733",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74495/"
] |
I'm using Advanced Custom Fields and Content Protector plugins in trying to protect an iframe for eventbrite ticket registration that gets displayed through Event Calendar plugin. I believe I'm wrapping the part that displayed the iframe with the Content Protector shortcode, but it gets displayed anyway even before entering the password. How could I make it so the iframe is displayed only when the password is entered?
```
<?php
$password = get_post_custom_values('password');
if(!empty($password)){
echo do_shortcode("[content_protector password=". "'".$password[0]."']". do_action( 'tribe_events_single_event_after_the_meta' ). "[/content_protector]");
} else {
do_action( 'tribe_events_single_event_after_the_meta' );
}
?>
```
|
`do_action` does not return text, it just does the action. So, calling `do_action( 'tribe_events_single_event_after_the_meta' )` in your `do_shortcode` call there will cause the iframe to be output before the shortcode.
|
192,773 |
<p>Is it possible to replace a <code>get_template_directory()</code> in my child's functions.php file?</p>
<p>I want to make changes to the file:</p>
<pre><code>/**
* Load Custom Post types file.
*/
require get_template_directory() . '/inc/post-types.php';
</code></pre>
<p>I'd obviously prefer my work not be overwritten when I update my theme, so can I un-register the parent file and then re-register my child's file in my child's functions file?</p>
|
[
{
"answer_id": 192774,
"author": "James Barrett",
"author_id": 74733,
"author_profile": "https://wordpress.stackexchange.com/users/74733",
"pm_score": 4,
"selected": false,
"text": "<p>You need to use <code>get_stylesheet_directory_uri()</code> instead of <code>get_template_directory()</code> in your child theme.</p>\n<p>From the WordPress codex:</p>\n<blockquote>\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_directory_uri\" rel=\"noreferrer\">get_template_directory_uri()</a></p>\n<p>In the event that a child theme is being\nused, the parent theme directory URI will be returned.\nget_template_directory_uri() should be used for resources that are not\nintended to be included in/over-ridden by a child theme. Use\nget_stylesheet_directory_uri() to include resources that are intended\nto be included in/over-ridden by the child theme.</p>\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"noreferrer\">get_stylesheet_directory_uri()</a></p>\n<p>In the event a child theme is being used, this function will return\nthe child's theme directory URI. Use get_template_directory_uri() to\navoid being overridden by a child theme.</p>\n</blockquote>\n"
},
{
"answer_id": 248822,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 6,
"selected": true,
"text": "<p>Late answer, but in Wordpress 4.7 two new functions were introduced to address this question.</p>\n\n<p><code>get_theme_file_path()</code> (for absolute file paths) and <code>get_theme_file_uri()</code> (for URLs) work just like <code>get_template_part()</code> in that they will automatically look in the child theme for that file first, then fallback to the parent theme.</p>\n\n<p>In your example, you could rewrite it using 4.7 to look like this:</p>\n\n<pre><code>/**\n* Load Custom Post types file.\n*/\nrequire get_theme_file_path( 'inc/post-types.php' );\n</code></pre>\n\n<p>More information here: <a href=\"https://make.wordpress.org/core/2016/09/09/new-functions-hooks-and-behaviour-for-theme-developers-in-wordpress-4-7/\" rel=\"noreferrer\">https://make.wordpress.org/core/2016/09/09/new-functions-hooks-and-behaviour-for-theme-developers-in-wordpress-4-7/</a></p>\n"
}
] |
2015/06/27
|
[
"https://wordpress.stackexchange.com/questions/192773",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62370/"
] |
Is it possible to replace a `get_template_directory()` in my child's functions.php file?
I want to make changes to the file:
```
/**
* Load Custom Post types file.
*/
require get_template_directory() . '/inc/post-types.php';
```
I'd obviously prefer my work not be overwritten when I update my theme, so can I un-register the parent file and then re-register my child's file in my child's functions file?
|
Late answer, but in Wordpress 4.7 two new functions were introduced to address this question.
`get_theme_file_path()` (for absolute file paths) and `get_theme_file_uri()` (for URLs) work just like `get_template_part()` in that they will automatically look in the child theme for that file first, then fallback to the parent theme.
In your example, you could rewrite it using 4.7 to look like this:
```
/**
* Load Custom Post types file.
*/
require get_theme_file_path( 'inc/post-types.php' );
```
More information here: <https://make.wordpress.org/core/2016/09/09/new-functions-hooks-and-behaviour-for-theme-developers-in-wordpress-4-7/>
|
192,778 |
<p>So I have this array (just taking an example, it's dynamically built up):</p>
<pre><code>$v_values = array(
array("C1","C2"),
array("F1","F2")
);
$v_name = array("color","fabric");
$v_price = array(
array(1000,2000),
array(3000,4000)
);
</code></pre>
<p>Now I want to create a product with variation, so this is the code:</p>
<pre><code> for($i = 0; $i < count($v_name); $i++) {
for($j = 0; $j < count($v_values[$i]); $j++) {
$var_post = array(
'post_title' => $ins["title"],
'post_content' => $ins["desc"] ,
'post_status' => ($user->roles[0] === "pending_vendor") ? 'pending' : 'publish',
'post_parent' => $post_id,
'post_type' => 'product_variation',
);
// Insert the post into the database
$var_post_id = wp_insert_post( $var_post );
update_post_meta($var_post_id, 'attribute_' . $v_name[$i], $v_values[$i][$j]);
update_post_meta($var_post_id, '_price', $v_price[$i][$j]);
update_post_meta($var_post_id, '_regular_price', (string) $v_price[$i][$j]);
for($k = 0; $k < count($v_name); $k++) {
if($i !== $k) {
for($l = 0; $l < count($v_values[$k]); $l++) {
update_post_meta($var_post_id, 'attribute_' . $v_name[$k], $v_values[$k][$l]);
update_post_meta($var_post_id, '_price', $v_price[$k][$l]);
update_post_meta($var_post_id, '_regular_price', (string) $v_price[$k][$l]);
}
}
}
}
}
</code></pre>
<p><em>Assume <code>$ins</code> variable is defined and <code>$post_id</code> is the parent post.</em></p>
<p><strong>The problem:</strong></p>
<p>The above code creates the following variation:</p>
<pre><code>| C1 | F2 |
---------
| C2 | F2 |
---------
| C2 | F1 |
---------
| C2 | F2 |
</code></pre>
<p>What was expected:</p>
<pre><code>| C1 | F1 |
---------
| C1 | F2 |
---------
| C2 | F1 |
---------
| C2 | F2 |
</code></pre>
<p>Cannot figure out a way, please help!</p>
|
[
{
"answer_id": 192809,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>with your code, you have this : </p>\n\n<blockquote>\n <p>+++++++++++++++++++++++++++++++++++++++++++++++++++\n attribute_color = C1<br>\n attribute_fabric = F1<br>\n attribute_fabric = F2<br>\n +++++++++++++++++++++++++++++++++++++++++++++++++++\n attribute_color = C2<br>\n attribute_fabric = F1<br>\n attribute_fabric = F2<br>\n +++++++++++++++++++++++++++++++++++++++++++++++++++\n attribute_fabric = F1<br>\n attribute_color = C1<br>\n attribute_color = C2<br>\n +++++++++++++++++++++++++++++++++++++++++++++++++++\n attribute_fabric = F2<br>\n attribute_color = C1<br>\n attribute_color = C2 </p>\n</blockquote>\n\n<p>if you have 2 name in $v_name, try this to have all combinations</p>\n\n<pre><code>foreach ($v_values[0] as $i0 => $v0) {\n\n foreach ($v_values[1] as $i1 => $v1) {\n\n $var_post = array(\n 'post_title' => $ins[\"title\"],\n 'post_content' => $ins[\"desc\"] ,\n 'post_status' => ($user->roles[0] === \"pending_vendor\") ? 'pending' : 'publish',\n 'post_parent' => $post_id,\n 'post_type' => 'product_variation',\n );\n\n // Insert the post into the database\n $var_post_id = wp_insert_post( $var_post );\n\n update_post_meta($var_post_id, 'attribute_' . $v_name[0], $v0);\n update_post_meta($var_post_id, 'attribute_' . $v_name[1], $v1);\n\n update_post_meta($var_post_id, '_price', $v_price[$i0][$i1]);\n update_post_meta($var_post_id, '_regular_price', (string) $v_price[$i0][$i1]);\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 192816,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>I found a solution with a recursive function </p>\n\n<pre><code>function decomposePrice($base, $iValue, $values, $prices) {\n\n $d = array();\n\n foreach ($prices as $i => $p) {\n\n $baseP = \"$base{$values[$iValue][$i]}|\";\n\n if (!is_array($p)) {\n $d[$baseP] = $p;\n } else {\n $d = array_merge($d, decomposePrice($baseP, $iValue + 1, $values, $p));\n }\n\n }\n\n return $d;\n}\n\n\n$decomposePrice = decomposePrice(\"\", 0, $v_values, $v_price);\n\n\nforeach ($decomposePrice as $att => $price) {\n\n\n $var_post = array(\n 'post_title' => $ins[\"title\"],\n 'post_content' => $ins[\"desc\"] ,\n 'post_status' => ($user->roles[0] === \"pending_vendor\") ? 'pending' : 'publish',\n 'post_parent' => $post_id,\n 'post_type' => 'product_variation',\n );\n\n // Insert the post into the database\n $var_post_id = wp_insert_post( $var_post );\n\n update_post_meta($var_post_id, '_price', $price);\n update_post_meta($var_post_id, '_regular_price', (string) $price);\n\n\n // attributes\n\n $list = explode(\"|\", $att);\n array_pop($list);\n\n foreach ($list as $iName => $value) {\n update_post_meta($var_post_id, 'attribute_' . $v_name[$iName], $value);\n }\n\n}\n</code></pre>\n"
}
] |
2015/06/27
|
[
"https://wordpress.stackexchange.com/questions/192778",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75314/"
] |
So I have this array (just taking an example, it's dynamically built up):
```
$v_values = array(
array("C1","C2"),
array("F1","F2")
);
$v_name = array("color","fabric");
$v_price = array(
array(1000,2000),
array(3000,4000)
);
```
Now I want to create a product with variation, so this is the code:
```
for($i = 0; $i < count($v_name); $i++) {
for($j = 0; $j < count($v_values[$i]); $j++) {
$var_post = array(
'post_title' => $ins["title"],
'post_content' => $ins["desc"] ,
'post_status' => ($user->roles[0] === "pending_vendor") ? 'pending' : 'publish',
'post_parent' => $post_id,
'post_type' => 'product_variation',
);
// Insert the post into the database
$var_post_id = wp_insert_post( $var_post );
update_post_meta($var_post_id, 'attribute_' . $v_name[$i], $v_values[$i][$j]);
update_post_meta($var_post_id, '_price', $v_price[$i][$j]);
update_post_meta($var_post_id, '_regular_price', (string) $v_price[$i][$j]);
for($k = 0; $k < count($v_name); $k++) {
if($i !== $k) {
for($l = 0; $l < count($v_values[$k]); $l++) {
update_post_meta($var_post_id, 'attribute_' . $v_name[$k], $v_values[$k][$l]);
update_post_meta($var_post_id, '_price', $v_price[$k][$l]);
update_post_meta($var_post_id, '_regular_price', (string) $v_price[$k][$l]);
}
}
}
}
}
```
*Assume `$ins` variable is defined and `$post_id` is the parent post.*
**The problem:**
The above code creates the following variation:
```
| C1 | F2 |
---------
| C2 | F2 |
---------
| C2 | F1 |
---------
| C2 | F2 |
```
What was expected:
```
| C1 | F1 |
---------
| C1 | F2 |
---------
| C2 | F1 |
---------
| C2 | F2 |
```
Cannot figure out a way, please help!
|
I found a solution with a recursive function
```
function decomposePrice($base, $iValue, $values, $prices) {
$d = array();
foreach ($prices as $i => $p) {
$baseP = "$base{$values[$iValue][$i]}|";
if (!is_array($p)) {
$d[$baseP] = $p;
} else {
$d = array_merge($d, decomposePrice($baseP, $iValue + 1, $values, $p));
}
}
return $d;
}
$decomposePrice = decomposePrice("", 0, $v_values, $v_price);
foreach ($decomposePrice as $att => $price) {
$var_post = array(
'post_title' => $ins["title"],
'post_content' => $ins["desc"] ,
'post_status' => ($user->roles[0] === "pending_vendor") ? 'pending' : 'publish',
'post_parent' => $post_id,
'post_type' => 'product_variation',
);
// Insert the post into the database
$var_post_id = wp_insert_post( $var_post );
update_post_meta($var_post_id, '_price', $price);
update_post_meta($var_post_id, '_regular_price', (string) $price);
// attributes
$list = explode("|", $att);
array_pop($list);
foreach ($list as $iName => $value) {
update_post_meta($var_post_id, 'attribute_' . $v_name[$iName], $value);
}
}
```
|
192,781 |
<p>I need some kind of plugin (if it exists) or a wp query which would display number of posts published within a certain time range.</p>
<p><em>For example:</em></p>
<p>I need to know how many posts have been published since 2015-06-01 until now -- 2015-06-27.</p>
<p>I really hope someone could help me out.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 192782,
"author": "Mitul",
"author_id": 74728,
"author_profile": "https://wordpress.stackexchange.com/users/74728",
"pm_score": 1,
"selected": false,
"text": "<p>You can fetch the record using bellow query </p>\n\n<pre><code>$posts= get_posts(array(\n 'numberposts' => -1,\n 'post_status' => 'publish',\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'date_query' => array(\n 'column' => 'post_date',\n 'after' => '-7 days' // -7 Means last 7 days \n )\n ));\necho count($posts);\n</code></pre>\n\n<p>If you want to get last 6 month the use -6 Months</p>\n"
},
{
"answer_id": 328377,
"author": "Sandra",
"author_id": 126017,
"author_profile": "https://wordpress.stackexchange.com/users/126017",
"pm_score": 0,
"selected": false,
"text": "<p>see also <a href=\"https://wordpress.stackexchange.com/questions/275654/user-published-post-count\">User Published Post Count</a></p>\n\n<p>if you've got many posts, you may want to use WP Query</p>\n\n<p><code>date_query</code> has been available since version 3.7</p>\n\n<pre><code>$args = [\n 'author' => $user_id, \n 'posts_per_page' => 1, //don't need more\n 'fields' => 'ids', //don't need more\n 'suppress_filters' => true, \n 'date_query' => ['after' => '-6 months']\n];\n\n$query = new WP_Query( $args ); \n$count_per_author = $query->found_posts; //how many posts match the query args\n</code></pre>\n\n<p><code>post_count</code> is used for how many posts are displayed</p>\n\n<p>for between date A and date B, you can use</p>\n\n<pre><code>'date_query' => [\n 'after' => '1 January 2019',\n 'before' => '31 January 2019'\n],\n\n'inclusive' => true,\n</code></pre>\n\n<p>see the WP Codex for more details on <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">WP Query</a>, inc. examples of how to use the <code>date</code> args and <code>inclusive</code> to match exact date values</p>\n"
}
] |
2015/06/27
|
[
"https://wordpress.stackexchange.com/questions/192781",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75317/"
] |
I need some kind of plugin (if it exists) or a wp query which would display number of posts published within a certain time range.
*For example:*
I need to know how many posts have been published since 2015-06-01 until now -- 2015-06-27.
I really hope someone could help me out.
Thanks.
|
You can fetch the record using bellow query
```
$posts= get_posts(array(
'numberposts' => -1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'date_query' => array(
'column' => 'post_date',
'after' => '-7 days' // -7 Means last 7 days
)
));
echo count($posts);
```
If you want to get last 6 month the use -6 Months
|
192,785 |
<p>The concept is to put a Button in Post Content which the user will click. </p>
<p>Two things - The ID of the post and Number of times the user clicks the Button should be displayed.</p>
<p>Reason - With this we are presenting Posts as Products and with that button user can add products,
and number of clicks on the button will signify the quantity that he wants.</p>
<p>The logic is working well with the normal php session, but not working with WP_Session using WP Session Manager plugin by Eric Mann which is considered as a standard way for using sessions in WP.</p>
<p>Working php session code - <a href="https://gist.github.com/vajrasar/8a8aa97de1b39f18ef29" rel="nofollow">Github</a></p>
<p>Using WP_Sessions it successfully displays what it should the first time when the button is clicked but never on multiple clicks. Never.</p>
<p>This is in Custom.js file ---></p>
<pre><code>jQuery( '.click' ).on( 'click', function() {
var post_id = jQuery( this ).attr( "data-id" );
var thisis = jQuery( this );
jQuery.ajax({
url: postcustom.ajax_url,
type: 'post',
data: {
action: 'vg_show_post_id',
post_id: post_id,
},
success: function( response ) {
jQuery( thisis.next( '#after-ajax' ) ).fadeIn( "slow" );
jQuery( thisis.next( '#after-ajax' ) ).text( "Item is added to the cart!" );
jQuery( '#session-sidebar' ).html( response );
jQuery( thisis.next( '#after-ajax' ) ).fadeOut( "slow" );
}
});
});
</code></pre>
<p>This is in functions.php File ---></p>
<pre><code><?php
/*****************************
*
* Ajax Stuff
*
********************************/
function vg_session_start() {
global $wp_session;
global $cart;
global $counter;
$wp_session = WP_Session::get_instance();
if( !empty( $cart ) ) {
$cart = $wp_session['wpscart']->toArray();
}
}
add_action( 'init', 'vg_session_start' ); // Starting Session
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'customjs', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true );
wp_localize_script( 'customjs', 'postcustom', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' ); // Enqueueing Scripts
function vg_after_entry() {
?>
<button type="button" class="click" href="#" data-id="<?php echo get_the_ID(); ?>">Submit</button>
<div id="after-ajax">
<!-- to do post ajax stuff -->
</div>
<?php
}
add_action( genesis_entry_footer, vg_after_entry ); // Adding button in post content
function vg_show_post_id() {
global $wp_session;
global $cart;
$wp_session = WP_Session::get_instance();
$cart = $wp_session['wpscart']->toArray();
$p_id = $_REQUEST['post_id'];
$title = get_the_title( $p_id );
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
if ( !empty( $cart ) && array_key_exists( $p_id, $cart ) ) {
$cnt = $cart[$p_id];
$cnt++;
$cart[$p_id] = $cnt;
} else {
$cart[$p_id] = 1;
}
foreach( $cart as $key=>$value ) {
echo "<br />" . get_the_title( $key ) . " " . $value . " units";
echo "<hr />";
}
$wp_session['wpscart'] = $cart;
die();
} else {
echo "Not in admin-ajax";
}
}
add_action( 'wp_ajax_nopriv_vg_show_post_id', 'vg_show_post_id' ); // for ajax
add_action( 'wp_ajax_vg_show_post_id', 'vg_show_post_id' ); // for ajax
</code></pre>
<p>Just to add to this, one major error shows up everytime - <code>Fatal error: Call to a member function toArray() on a non-object in /home/xxxxx/public_html/bcm/wp-content/themes/genesis-sample/functions.php on line 88</code> which has this code - <code>$cart = $wp_session['wpscart']->toArray();</code></p>
|
[
{
"answer_id": 193049,
"author": "Hari Om Gupta",
"author_id": 68792,
"author_profile": "https://wordpress.stackexchange.com/users/68792",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need to start session at init action, find the piece of code given below..\nmay be helpful to you. :)</p>\n\n<pre><code> add_action('init','vg_session_start');\n function vg_session_start(){\n if( !session_id() )\n session_start();\n }\n ...... your code.....\n</code></pre>\n"
},
{
"answer_id": 193501,
"author": "Sam Loyer",
"author_id": 75577,
"author_profile": "https://wordpress.stackexchange.com/users/75577",
"pm_score": 1,
"selected": false,
"text": "<p>I think in your code you must add this line for ajax acting</p>\n\n<pre><code>jQuery.ajax({\ntype : 'POST',\nurl : '<?php echo admin_url('admin-ajax.php'); ?>',\ndata : { action : 'vg_show_post_id', post_id: $post_id, data-id: true },\n),\n</code></pre>\n"
}
] |
2015/06/27
|
[
"https://wordpress.stackexchange.com/questions/192785",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19409/"
] |
The concept is to put a Button in Post Content which the user will click.
Two things - The ID of the post and Number of times the user clicks the Button should be displayed.
Reason - With this we are presenting Posts as Products and with that button user can add products,
and number of clicks on the button will signify the quantity that he wants.
The logic is working well with the normal php session, but not working with WP\_Session using WP Session Manager plugin by Eric Mann which is considered as a standard way for using sessions in WP.
Working php session code - [Github](https://gist.github.com/vajrasar/8a8aa97de1b39f18ef29)
Using WP\_Sessions it successfully displays what it should the first time when the button is clicked but never on multiple clicks. Never.
This is in Custom.js file --->
```
jQuery( '.click' ).on( 'click', function() {
var post_id = jQuery( this ).attr( "data-id" );
var thisis = jQuery( this );
jQuery.ajax({
url: postcustom.ajax_url,
type: 'post',
data: {
action: 'vg_show_post_id',
post_id: post_id,
},
success: function( response ) {
jQuery( thisis.next( '#after-ajax' ) ).fadeIn( "slow" );
jQuery( thisis.next( '#after-ajax' ) ).text( "Item is added to the cart!" );
jQuery( '#session-sidebar' ).html( response );
jQuery( thisis.next( '#after-ajax' ) ).fadeOut( "slow" );
}
});
});
```
This is in functions.php File --->
```
<?php
/*****************************
*
* Ajax Stuff
*
********************************/
function vg_session_start() {
global $wp_session;
global $cart;
global $counter;
$wp_session = WP_Session::get_instance();
if( !empty( $cart ) ) {
$cart = $wp_session['wpscart']->toArray();
}
}
add_action( 'init', 'vg_session_start' ); // Starting Session
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'customjs', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true );
wp_localize_script( 'customjs', 'postcustom', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' ); // Enqueueing Scripts
function vg_after_entry() {
?>
<button type="button" class="click" href="#" data-id="<?php echo get_the_ID(); ?>">Submit</button>
<div id="after-ajax">
<!-- to do post ajax stuff -->
</div>
<?php
}
add_action( genesis_entry_footer, vg_after_entry ); // Adding button in post content
function vg_show_post_id() {
global $wp_session;
global $cart;
$wp_session = WP_Session::get_instance();
$cart = $wp_session['wpscart']->toArray();
$p_id = $_REQUEST['post_id'];
$title = get_the_title( $p_id );
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
if ( !empty( $cart ) && array_key_exists( $p_id, $cart ) ) {
$cnt = $cart[$p_id];
$cnt++;
$cart[$p_id] = $cnt;
} else {
$cart[$p_id] = 1;
}
foreach( $cart as $key=>$value ) {
echo "<br />" . get_the_title( $key ) . " " . $value . " units";
echo "<hr />";
}
$wp_session['wpscart'] = $cart;
die();
} else {
echo "Not in admin-ajax";
}
}
add_action( 'wp_ajax_nopriv_vg_show_post_id', 'vg_show_post_id' ); // for ajax
add_action( 'wp_ajax_vg_show_post_id', 'vg_show_post_id' ); // for ajax
```
Just to add to this, one major error shows up everytime - `Fatal error: Call to a member function toArray() on a non-object in /home/xxxxx/public_html/bcm/wp-content/themes/genesis-sample/functions.php on line 88` which has this code - `$cart = $wp_session['wpscart']->toArray();`
|
I think in your code you must add this line for ajax acting
```
jQuery.ajax({
type : 'POST',
url : '<?php echo admin_url('admin-ajax.php'); ?>',
data : { action : 'vg_show_post_id', post_id: $post_id, data-id: true },
),
```
|
192,789 |
<p>Is it possible to add a CSS class to ALL links generated from the HTML tab of the post editor?</p>
<p>That is to have the part class='myclass" added automatically?</p>
<pre><code><a class="myclass" href="http://www.google.com">Click me</a>
</code></pre>
<p>EDIT to avoid misunderstanding: The class has to be added in the editor and not on the fly via javascript or HTML and this is because not all the links will use this class so in the rare case where I don't need it, I simply remove it myself. At the moment I'm doing the complete opposite, I keep adding class="myclass" myself which can be a nuisance in case of a post with 20 or more links.</p>
|
[
{
"answer_id": 192791,
"author": "cptstarling",
"author_id": 74024,
"author_profile": "https://wordpress.stackexchange.com/users/74024",
"pm_score": 1,
"selected": false,
"text": "<p>It would be more efficient to add a container with a certain class name around content that has been created with the HTML tab. That way you're avoiding the code getting bulky.</p>\n"
},
{
"answer_id": 192793,
"author": "Macerier",
"author_id": 75321,
"author_profile": "https://wordpress.stackexchange.com/users/75321",
"pm_score": 1,
"selected": false,
"text": "<p>you can use:</p>\n\n<pre><code>add_filter('the_content', 'addClassToLinks');\nfunction addClassToLinks($content){\n return str_replace( '<a ', \"<a class='myclass'\", $content);\n}\n</code></pre>\n\n<p>But i don't recommend it.</p>\n\n<p>Just add in theme an specific class for container of the content.\nIt is cleaner and use in css:</p>\n\n<pre><code>.myclass a {\n // css for a that is fount inside myclass\n}\n</code></pre>\n"
},
{
"answer_id": 192794,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>As suggested, just add a container around the content. You do not want to <code>str_replace()</code> or <code>preg_replace()</code> your markup. It is resource expensive and prone to error. So...</p>\n\n<pre><code><div class=\"html-content\"><?php\n the_content(); ?>\n</div>\n</code></pre>\n\n<p>Then...</p>\n\n<pre><code>.html-content a { }\n</code></pre>\n\n<p>In fact, chances are you already have markup in your theme similar enough to that for this to work without further change. </p>\n\n<p>You could do the same with a filter:</p>\n\n<pre><code>function add_content_wrapper($content) {\n $content = '<div class=\"html-content\">'.$content.'</div>';\n return $content;\n}\nadd_filter('the_content','add_content_wrapper');\n</code></pre>\n"
},
{
"answer_id": 192800,
"author": "Ravinder Kumar",
"author_id": 29439,
"author_profile": "https://wordpress.stackexchange.com/users/29439",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://wordpress.org/plugins/tinymce-advanced/\" rel=\"nofollow noreferrer\">Advanced Tinymce</a> plugin to solve your problem.</p>\n\n<blockquote>\n <p>This plugin enables the advanced features of TinyMCE, the WordPress WYSIWYG editor. It includes 15 plugins for TinyMCE that are automatically enabled or disabled depending on what buttons are chosen.</p>\n</blockquote>\n\n<p>You can see <a href=\"https://wordpress.stackexchange.com/questions/53812/add-a-class-to-links-in-the-visual-editor-how-to-get-old-dialog-back\">demo</a> here.</p>\n"
}
] |
2015/06/27
|
[
"https://wordpress.stackexchange.com/questions/192789",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54737/"
] |
Is it possible to add a CSS class to ALL links generated from the HTML tab of the post editor?
That is to have the part class='myclass" added automatically?
```
<a class="myclass" href="http://www.google.com">Click me</a>
```
EDIT to avoid misunderstanding: The class has to be added in the editor and not on the fly via javascript or HTML and this is because not all the links will use this class so in the rare case where I don't need it, I simply remove it myself. At the moment I'm doing the complete opposite, I keep adding class="myclass" myself which can be a nuisance in case of a post with 20 or more links.
|
It would be more efficient to add a container with a certain class name around content that has been created with the HTML tab. That way you're avoiding the code getting bulky.
|
192,805 |
<p>For example,any "naked" code, i.e.:</p>
<pre><code>IF ($_POST) then....,
</code></pre>
<p>runs directly, before any WP action.
for example, this runs later (even with point 1):</p>
<pre><code>add_action('init','my_function',1);
</code></pre>
<p>I want to execute my code before any WP action starts. Which hook executes at first?</p>
|
[
{
"answer_id": 192791,
"author": "cptstarling",
"author_id": 74024,
"author_profile": "https://wordpress.stackexchange.com/users/74024",
"pm_score": 1,
"selected": false,
"text": "<p>It would be more efficient to add a container with a certain class name around content that has been created with the HTML tab. That way you're avoiding the code getting bulky.</p>\n"
},
{
"answer_id": 192793,
"author": "Macerier",
"author_id": 75321,
"author_profile": "https://wordpress.stackexchange.com/users/75321",
"pm_score": 1,
"selected": false,
"text": "<p>you can use:</p>\n\n<pre><code>add_filter('the_content', 'addClassToLinks');\nfunction addClassToLinks($content){\n return str_replace( '<a ', \"<a class='myclass'\", $content);\n}\n</code></pre>\n\n<p>But i don't recommend it.</p>\n\n<p>Just add in theme an specific class for container of the content.\nIt is cleaner and use in css:</p>\n\n<pre><code>.myclass a {\n // css for a that is fount inside myclass\n}\n</code></pre>\n"
},
{
"answer_id": 192794,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>As suggested, just add a container around the content. You do not want to <code>str_replace()</code> or <code>preg_replace()</code> your markup. It is resource expensive and prone to error. So...</p>\n\n<pre><code><div class=\"html-content\"><?php\n the_content(); ?>\n</div>\n</code></pre>\n\n<p>Then...</p>\n\n<pre><code>.html-content a { }\n</code></pre>\n\n<p>In fact, chances are you already have markup in your theme similar enough to that for this to work without further change. </p>\n\n<p>You could do the same with a filter:</p>\n\n<pre><code>function add_content_wrapper($content) {\n $content = '<div class=\"html-content\">'.$content.'</div>';\n return $content;\n}\nadd_filter('the_content','add_content_wrapper');\n</code></pre>\n"
},
{
"answer_id": 192800,
"author": "Ravinder Kumar",
"author_id": 29439,
"author_profile": "https://wordpress.stackexchange.com/users/29439",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://wordpress.org/plugins/tinymce-advanced/\" rel=\"nofollow noreferrer\">Advanced Tinymce</a> plugin to solve your problem.</p>\n\n<blockquote>\n <p>This plugin enables the advanced features of TinyMCE, the WordPress WYSIWYG editor. It includes 15 plugins for TinyMCE that are automatically enabled or disabled depending on what buttons are chosen.</p>\n</blockquote>\n\n<p>You can see <a href=\"https://wordpress.stackexchange.com/questions/53812/add-a-class-to-links-in-the-visual-editor-how-to-get-old-dialog-back\">demo</a> here.</p>\n"
}
] |
2015/06/27
|
[
"https://wordpress.stackexchange.com/questions/192805",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
] |
For example,any "naked" code, i.e.:
```
IF ($_POST) then....,
```
runs directly, before any WP action.
for example, this runs later (even with point 1):
```
add_action('init','my_function',1);
```
I want to execute my code before any WP action starts. Which hook executes at first?
|
It would be more efficient to add a container with a certain class name around content that has been created with the HTML tab. That way you're avoiding the code getting bulky.
|
192,854 |
<p>I'll try explain this the best I can...</p>
<p>I have a search form on my homepage:</p>
<pre><code><form role="search" method="get" id="searchform" class="form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label class="u-visuallyHidden" for="s">Search for property:</label>
<input type="search" class="form-input search-bar-input" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder="enter location here" autocomplete="off" />
<button type="submit" class="btn search-bar-btn" id="searchsubmit">
<span class="u-verticalAlignMiddle"><i class="icon-search"></i> <span class="u-visuallyHidden">Search</span></span>
</button>
</form>
</code></pre>
<p>And then there's more in-depth search form in my 'search.php' template that holds a number of hidden fields that relate to some user input selectors. The search results then take the <code>$_GET</code> request and I build a custom <code>$wp_query</code>.</p>
<p>Everything works fine...but, I'd like to change my search URL to something like:</p>
<pre><code>http://mydomain.dev/student/?s=
</code></pre>
<p>I've tried to change the action to <code>esc_url( home_url( '/student/' ) )</code> but I just get a 404 when a search term is entered.</p>
<p>I've played around with the 'template_redirect' action and rewrite rules, but I don't want pretty permalinks because my refined search form adds a number of additional URL params. For example a users search could yield this URL:</p>
<pre><code>http://mydomain.dev/?s=&letmc_type=professional&custom_locations=SomeCity&min_bedrooms=2&price_min=60&price_max=70
</code></pre>
<p>Also, is there a better way with WordPress of utilizing query args, rather than the <code>$_GET</code> superglobal?</p>
|
[
{
"answer_id": 192856,
"author": "lucian",
"author_id": 70333,
"author_profile": "https://wordpress.stackexchange.com/users/70333",
"pm_score": 1,
"selected": false,
"text": "<p>The default \"pretty\" alternative to <code>?s=</code> is <code>/search/</code> - you should be able to use that right now.</p>\n\n<p>If you want to change it to student, add this to your functions.php file:</p>\n\n<pre><code>function re_rewrite_rules() {\n global $wp_rewrite;\n $wp_rewrite->search_base = 'student';\n}\nadd_action('init', 're_rewrite_rules');\n</code></pre>\n"
},
{
"answer_id": 344811,
"author": "Adebowale",
"author_id": 152934,
"author_profile": "https://wordpress.stackexchange.com/users/152934",
"pm_score": 0,
"selected": false,
"text": "<p>This works perfectly for me on my site: <a href=\"https://nnn.com.ng/\" rel=\"nofollow noreferrer\">nnn.com.ng</a>. Other solution throw a 404 error for me.</p>\n\n<pre><code>/**\n* initiate a change of the wordpress default search page slug to the new search page slug.\n*/\nadd_action( 'init', 'dsfs' );\n\nfunction dsfs()\n{\n $GLOBALS['wp_rewrite']->search_base = '%your_search_string%';\n}\n\n/**\n* redirect default search page slug to the new search page slug.\n*/\n\nfunction wpcs_url() {\n if ( is_search() && ! empty( $_GET['s'] ) ) {\n wp_redirect( home_url( \"/your_search_string/\" ) . urlencode( get_query_var( 's' ) ) );\n exit();\n } \n}\nadd_action( 'template_redirect', 'wpcs_url' );\n</code></pre>\n\n<p>You will need to add \"%\" before and after \"your_search_string\" (e.g. %student%) for it to work. You may need to flush the cache if it is a production site with a cache plugin.</p>\n"
},
{
"answer_id": 390951,
"author": "davey",
"author_id": 128873,
"author_profile": "https://wordpress.stackexchange.com/users/128873",
"pm_score": 2,
"selected": false,
"text": "<p>None of the above worked for me. Found another solution by overwriting the search rewrite rules using the search_rewrite_rules filter.</p>\n<p>1 - Add this to the functions.php of your theme:</p>\n<pre><code>add_filter( 'search_rewrite_rules', function($rules) {\n \n $new_rules = [];\n\n // New search slug here\n $new_search_slug = 'zoeken';\n \n foreach ($rules AS $key => $value){\n \n $new_rules[str_replace('search', $new_search_slug, $key)] = $value;\n \n }\n\n return $new_rules;\n\n});\n</code></pre>\n<p>2 - Save the permalinks in the WordPress admin under Settings -> Permalinks.</p>\n<p>Now the page <a href=\"https://www.mywebsite.com/zoeken/searchterm\" rel=\"nofollow noreferrer\">https://www.mywebsite.com/zoeken/searchterm</a> is showing the search results page.</p>\n"
}
] |
2015/06/28
|
[
"https://wordpress.stackexchange.com/questions/192854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51284/"
] |
I'll try explain this the best I can...
I have a search form on my homepage:
```
<form role="search" method="get" id="searchform" class="form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label class="u-visuallyHidden" for="s">Search for property:</label>
<input type="search" class="form-input search-bar-input" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder="enter location here" autocomplete="off" />
<button type="submit" class="btn search-bar-btn" id="searchsubmit">
<span class="u-verticalAlignMiddle"><i class="icon-search"></i> <span class="u-visuallyHidden">Search</span></span>
</button>
</form>
```
And then there's more in-depth search form in my 'search.php' template that holds a number of hidden fields that relate to some user input selectors. The search results then take the `$_GET` request and I build a custom `$wp_query`.
Everything works fine...but, I'd like to change my search URL to something like:
```
http://mydomain.dev/student/?s=
```
I've tried to change the action to `esc_url( home_url( '/student/' ) )` but I just get a 404 when a search term is entered.
I've played around with the 'template\_redirect' action and rewrite rules, but I don't want pretty permalinks because my refined search form adds a number of additional URL params. For example a users search could yield this URL:
```
http://mydomain.dev/?s=&letmc_type=professional&custom_locations=SomeCity&min_bedrooms=2&price_min=60&price_max=70
```
Also, is there a better way with WordPress of utilizing query args, rather than the `$_GET` superglobal?
|
None of the above worked for me. Found another solution by overwriting the search rewrite rules using the search\_rewrite\_rules filter.
1 - Add this to the functions.php of your theme:
```
add_filter( 'search_rewrite_rules', function($rules) {
$new_rules = [];
// New search slug here
$new_search_slug = 'zoeken';
foreach ($rules AS $key => $value){
$new_rules[str_replace('search', $new_search_slug, $key)] = $value;
}
return $new_rules;
});
```
2 - Save the permalinks in the WordPress admin under Settings -> Permalinks.
Now the page <https://www.mywebsite.com/zoeken/searchterm> is showing the search results page.
|
192,872 |
<p>I am a content supervisor on a wordpress site, it uses <a href="https://wordpress.org/plugins/wordpress-seo/" rel="nofollow">wordpress seo by yoast</a> plugin. My duty includes analyzing the content and marking it sticky if seems fit. When I mark a particular post as sticky, there is a function which then sets the post to only appear on the category page. Next thing I have to do is manually set the single-post-view to no-index as instructed by the site-owner.</p>
<p>Since the site is huge, this process is really getting tedious so I am looking for a way to partly automate this process. I am trying to put together a function, which sets the post to no-index, as soon as I update the post as sticky.</p>
<p>First, I would like to know which wp-function is fired when a post is set to sticky. Second, since the site uses <a href="https://wordpress.org/plugins/wordpress-seo/" rel="nofollow">yoast's seo-plugin</a>, I would like to know about the seo-plugin's hook/filter which sets the post to no-index. Looking for relevant filters or hooks I found the <a href="https://yoast.com/wordpress/plugins/seo/api/" rel="nofollow">seo-plugin API</a> page of yoast which has a few filters but I could not find anything that could be useful for my purpose.</p>
|
[
{
"answer_id": 192874,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you just check if the post is sticky and then add noindex? You can use the <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\">Conditional Tag</a> <code>is_sticky()</code>.</p>\n\n<p>So, in your <code><head></code> tag in your <code>header.php</code> file, do the following check:</p>\n\n<pre><code>if ( is_sticky() && is_single() ) {\n // it's a post and it's sticky, let's add noindex\n echo '<meta name=\"robots\" content=\"noindex\">';\n}\n</code></pre>\n"
},
{
"answer_id": 193035,
"author": "gurung",
"author_id": 25508,
"author_profile": "https://wordpress.stackexchange.com/users/25508",
"pm_score": 2,
"selected": true,
"text": "<p>In my effort to solve this I discovered a <a href=\"http://hookr.io/\" rel=\"nofollow\">great resource for wordpress hooks</a> for the job and found the right hook <code>wpseo_saved_postdata</code> <a href=\"http://hookr.io/actions/wpseo_saved_postdata/\" rel=\"nofollow\">here</a>. Feel free to modify the code if you think it could be better. For now, it works for me.</p>\n\n<pre><code>function set_noidex_when_sticky($post_id){\n if ( wp_is_post_revision( $post_id ) ) return;\n //perform other checks\n\n //if(is_sticky($post_id)){ -----> this may work only AFTER the post is set to sticky\n if (isset($_POST['sticky']) == 'sticky') { //this will work if the post IS BEING SET ticky \n add_action( 'wpseo_saved_postdata', function() use ( $post_id ) { \n update_post_meta( $post_id, '_yoast_wpseo_meta-robots-noindex', '1' );\n }, 999 );\n }\n}\n add_action( 'save_post', 'set_noidex_when_sticky' );\n</code></pre>\n\n<p>Only <code>_yoast_wpseo_meta-robots-noindex</code> was the meta I was targeting to change. Given below are some of yoast's meta keys, if you wanna make any change using the code.</p>\n\n<pre><code>_yoast_wpseo_google-plus-description\n_yoast_wpseo_linkdex\n_yoast_wpseo_opengraph-description\n_yoast_wpseo_redirect\n_yoast_wpseo_canonical\n_yoast_wpseo_sitemap-html-include\n_yoast_wpseo_sitemap-prio\n_yoast_wpseo_sitemap-include\n_yoast_wpseo_meta-robots-adv\n_yoast_wpseo_meta-robots-nofollow\n_yoast_wpseo_meta-robots-noindex\n_yoast_wpseo_metadesc\n_yoast_wpseo_title\n</code></pre>\n"
}
] |
2015/06/28
|
[
"https://wordpress.stackexchange.com/questions/192872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25508/"
] |
I am a content supervisor on a wordpress site, it uses [wordpress seo by yoast](https://wordpress.org/plugins/wordpress-seo/) plugin. My duty includes analyzing the content and marking it sticky if seems fit. When I mark a particular post as sticky, there is a function which then sets the post to only appear on the category page. Next thing I have to do is manually set the single-post-view to no-index as instructed by the site-owner.
Since the site is huge, this process is really getting tedious so I am looking for a way to partly automate this process. I am trying to put together a function, which sets the post to no-index, as soon as I update the post as sticky.
First, I would like to know which wp-function is fired when a post is set to sticky. Second, since the site uses [yoast's seo-plugin](https://wordpress.org/plugins/wordpress-seo/), I would like to know about the seo-plugin's hook/filter which sets the post to no-index. Looking for relevant filters or hooks I found the [seo-plugin API](https://yoast.com/wordpress/plugins/seo/api/) page of yoast which has a few filters but I could not find anything that could be useful for my purpose.
|
In my effort to solve this I discovered a [great resource for wordpress hooks](http://hookr.io/) for the job and found the right hook `wpseo_saved_postdata` [here](http://hookr.io/actions/wpseo_saved_postdata/). Feel free to modify the code if you think it could be better. For now, it works for me.
```
function set_noidex_when_sticky($post_id){
if ( wp_is_post_revision( $post_id ) ) return;
//perform other checks
//if(is_sticky($post_id)){ -----> this may work only AFTER the post is set to sticky
if (isset($_POST['sticky']) == 'sticky') { //this will work if the post IS BEING SET ticky
add_action( 'wpseo_saved_postdata', function() use ( $post_id ) {
update_post_meta( $post_id, '_yoast_wpseo_meta-robots-noindex', '1' );
}, 999 );
}
}
add_action( 'save_post', 'set_noidex_when_sticky' );
```
Only `_yoast_wpseo_meta-robots-noindex` was the meta I was targeting to change. Given below are some of yoast's meta keys, if you wanna make any change using the code.
```
_yoast_wpseo_google-plus-description
_yoast_wpseo_linkdex
_yoast_wpseo_opengraph-description
_yoast_wpseo_redirect
_yoast_wpseo_canonical
_yoast_wpseo_sitemap-html-include
_yoast_wpseo_sitemap-prio
_yoast_wpseo_sitemap-include
_yoast_wpseo_meta-robots-adv
_yoast_wpseo_meta-robots-nofollow
_yoast_wpseo_meta-robots-noindex
_yoast_wpseo_metadesc
_yoast_wpseo_title
```
|
192,902 |
<p>I don't get any errors, but the post images are not displayed on the front page, all other pages displays the images correctly. How can I fix this? Here is the site</p>
<p>The front page is set to display the recent posts.</p>
<p>This is the index.php file</p>
<pre><code><?php get_header(); ?>
<?php
// get options
$pinthis_infinite_scroll = get_option('pbpanel_infinite_scroll');
?>
<section id="content">
<div class="container fluid">
<?php if (is_category()) { ?>
<div class="category-title">
<div class="container">
<h3 class="title-3"><?php single_cat_title(); ?></h3>
<?php if (category_description()) { ?><div class="description"><?php echo category_description(); ?></div><?php } ?>
</div>
</div>
<?php } ?>
<?php if ( have_posts() ) { ?>
<div class="boxcontainer">
<?php while ( have_posts() ) { the_post(); ?>
<?php get_template_part('pinbox', get_post_format()); ?>
<?php } ?>
</div>
<?php
ob_start();
posts_nav_link(' ', __('Previous Page', 'pinthis'), __('Next Page', 'pinthis'));
$pinthis_posts_nav_link = ob_get_clean();
?>
<?php if(strlen($pinthis_posts_nav_link) > 0) { ?>
<div class="container">
<div class="posts-navigation clearfix <?php if ($pinthis_infinite_scroll == 1) { ?>hide<?php } ?>"><?php echo $pinthis_posts_nav_link; ?></div>
</div>
<?php } ?>
<?php } else { ?>
<div class="notification-body">
<p class="notification tcenter"><?php echo __('No posts found.', 'pinthis'); ?></p>
</div>
<?php } ?>
</div>
</section>
<?php get_footer(); ?>
</code></pre>
|
[
{
"answer_id": 192903,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>Something that generates the image links is broken. You are not getting a valid <code>src</code> attribute in the <code>title</code> tag. The result is:</p>\n\n<pre><code><p class=\"thumb\">\n <a href=\"http://paper-backgrounds.com/red-grunge-concrete-texture-3/\" title=\"Red Grunge Concrete Texture\">\n <img src=\"undefined\" alt=\"Red Grunge Concrete Texture\" height=\"132\" width=\"236\">\n </a>\n</p>\n</code></pre>\n\n<p>Without that <code>src</code> attribute the image can't load. </p>\n\n<p>As you don't post the code that generated that HTML I can't say exactly how to fix it, but should you post that code (as an edit to the question) I am pretty sure it is an easy fix.</p>\n"
},
{
"answer_id": 192982,
"author": "Mahavar Hitesh",
"author_id": 75414,
"author_profile": "https://wordpress.stackexchange.com/users/75414",
"pm_score": 0,
"selected": false,
"text": "<p>Use This code.</p>\n\n<pre><code>if (wp_get_attachment_url(get_post_thumbnail_id($post->ID))) {\n $thumbnail_url = wp_get_attachment_url(get_post_thumbnail_id($post->ID));\n $data .= '<img alt=\"blog-img\" title=\"blog-img\" class=\"img-responsive\" src=\"' . $thumbnail_url . '\"/>';\n}\n</code></pre>\n"
}
] |
2015/06/29
|
[
"https://wordpress.stackexchange.com/questions/192902",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15760/"
] |
I don't get any errors, but the post images are not displayed on the front page, all other pages displays the images correctly. How can I fix this? Here is the site
The front page is set to display the recent posts.
This is the index.php file
```
<?php get_header(); ?>
<?php
// get options
$pinthis_infinite_scroll = get_option('pbpanel_infinite_scroll');
?>
<section id="content">
<div class="container fluid">
<?php if (is_category()) { ?>
<div class="category-title">
<div class="container">
<h3 class="title-3"><?php single_cat_title(); ?></h3>
<?php if (category_description()) { ?><div class="description"><?php echo category_description(); ?></div><?php } ?>
</div>
</div>
<?php } ?>
<?php if ( have_posts() ) { ?>
<div class="boxcontainer">
<?php while ( have_posts() ) { the_post(); ?>
<?php get_template_part('pinbox', get_post_format()); ?>
<?php } ?>
</div>
<?php
ob_start();
posts_nav_link(' ', __('Previous Page', 'pinthis'), __('Next Page', 'pinthis'));
$pinthis_posts_nav_link = ob_get_clean();
?>
<?php if(strlen($pinthis_posts_nav_link) > 0) { ?>
<div class="container">
<div class="posts-navigation clearfix <?php if ($pinthis_infinite_scroll == 1) { ?>hide<?php } ?>"><?php echo $pinthis_posts_nav_link; ?></div>
</div>
<?php } ?>
<?php } else { ?>
<div class="notification-body">
<p class="notification tcenter"><?php echo __('No posts found.', 'pinthis'); ?></p>
</div>
<?php } ?>
</div>
</section>
<?php get_footer(); ?>
```
|
Something that generates the image links is broken. You are not getting a valid `src` attribute in the `title` tag. The result is:
```
<p class="thumb">
<a href="http://paper-backgrounds.com/red-grunge-concrete-texture-3/" title="Red Grunge Concrete Texture">
<img src="undefined" alt="Red Grunge Concrete Texture" height="132" width="236">
</a>
</p>
```
Without that `src` attribute the image can't load.
As you don't post the code that generated that HTML I can't say exactly how to fix it, but should you post that code (as an edit to the question) I am pretty sure it is an easy fix.
|
192,917 |
<p>I want do a custom query to get all products with an especific attribute ("demo" in my case)
The query what i want returns from this:</p>
<pre><code>a:5:{s:4:"demo";
a:6:{s:4:"name";
s:4:"DEMO";
s:5:"value";
s:366:"LINK TO DEMO";
s:8:"position";
s:1:"0";
s:10:"is_visible";
i:0;
s:12:"is_variation";
i:0;
s:11:"is_taxonomy";
i:0;
}
</code></pre>
<p>}</p>
<p>I don't know how do an $args to get products. I want $args be something like this:</p>
<pre><code> $args = array (
'meta_query' => array(
array(
'key' => 'meta_value',
'value' => 'demo',
'compare' => 'LIKE', ),
),
);
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 192919,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>try something like this</p>\n\n<pre><code>$args = array(\n \"post_type\" => \"product\",\n \"meta_query\" => array(\n array(\n \"key\" => \"demo\",\n \"value\" => \"abc\",\n \"compare\" => \"EXISTS\",\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n"
},
{
"answer_id": 192920,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 2,
"selected": false,
"text": "<p>You have written <code>key</code> as <code>meta_value</code>. It should be your meta name. The name you have given to your custom fields or meta. Then use the following query.</p>\n\n<pre><code>$args = array ( \n 'post_type' => 'your-post-type',\n 'posts_per_page' => -1,\n 'meta_query' => array( \n array( \n 'key' => 'demo', \n 'value' => '',\n 'compare' => '!='\n ), \n ), \n );\n</code></pre>\n\n<p>By default the <code>compare</code> is set to <code>=</code></p>\n"
},
{
"answer_id": 192926,
"author": "C.B.",
"author_id": 75388,
"author_profile": "https://wordpress.stackexchange.com/users/75388",
"pm_score": 3,
"selected": true,
"text": "<p>OK I HAVE ALREADY!! yuhuuu!</p>\n\n<p>Thanks a lot guys!! </p>\n\n<p>I have this: </p>\n\n<pre><code>$args = array ( \n 'post_type' => 'product',\n 'posts_per_page' => -1,\n 'meta_query' => array( \n array( \n 'value' => 'demo', \n 'compare' => 'like'\n ), \n ),\n ); \n</code></pre>\n\n<p>Well this works at least for me</p>\n\n<p>Thanks thanks!!</p>\n\n<p>Best regards!</p>\n"
},
{
"answer_id": 321943,
"author": "ssaltman",
"author_id": 68638,
"author_profile": "https://wordpress.stackexchange.com/users/68638",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is old, but straight sql, here are my solutions:</p>\n\n<p>Get all meta data for a product:</p>\n\n<pre><code>SELECT meta_key, meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = 626\n</code></pre>\n\n<p>Get products with specific meta data</p>\n\n<pre><code>SELECT p.id, p.post_title, m.meta_key, m.meta_value FROM wp_posts p \nINNER JOIN wp_postmeta m ON p.id=m.post_id AND m.meta_key='_auction_dates_to' \n</code></pre>\n\n<p>APPEND TO GET META DATA FOR A SPECIFIC PRODUCT</p>\n\n<pre><code>AND p.id=626\n</code></pre>\n\n<p>Append to get specific meta value</p>\n\n<pre><code>AND m.meta_value='today'\n</code></pre>\n"
}
] |
2015/06/29
|
[
"https://wordpress.stackexchange.com/questions/192917",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75388/"
] |
I want do a custom query to get all products with an especific attribute ("demo" in my case)
The query what i want returns from this:
```
a:5:{s:4:"demo";
a:6:{s:4:"name";
s:4:"DEMO";
s:5:"value";
s:366:"LINK TO DEMO";
s:8:"position";
s:1:"0";
s:10:"is_visible";
i:0;
s:12:"is_variation";
i:0;
s:11:"is_taxonomy";
i:0;
}
```
}
I don't know how do an $args to get products. I want $args be something like this:
```
$args = array (
'meta_query' => array(
array(
'key' => 'meta_value',
'value' => 'demo',
'compare' => 'LIKE', ),
),
);
```
Thanks!
|
OK I HAVE ALREADY!! yuhuuu!
Thanks a lot guys!!
I have this:
```
$args = array (
'post_type' => 'product',
'posts_per_page' => -1,
'meta_query' => array(
array(
'value' => 'demo',
'compare' => 'like'
),
),
);
```
Well this works at least for me
Thanks thanks!!
Best regards!
|
192,944 |
<p>When I Import Mysql from local server to web ser it is showng me error</p>
<h1>1115 - Unknown character set: 'utf8mb4' in Creating wordpress wp_comment table</h1>
<pre><code>CREATE TABLE IF NOT EXISTS `wp_commentmeta` (
//
//
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 AUTO_INCREMENT =1;
#1115 - Unknown character set: 'utf8mb4'
</code></pre>
<p>My mysql version is</p>
<pre><code>Version information: 4.0.4, latest stable version: 4.4.10 (local version)
Version information: 4.0.10.7, latest stable version: 4.4.10( server version)
</code></pre>
<p>Please help me to solve out the error</p>
|
[
{
"answer_id": 198767,
"author": "Selorm",
"author_id": 73965,
"author_profile": "https://wordpress.stackexchange.com/users/73965",
"pm_score": -1,
"selected": false,
"text": "<p>simply open your exported database in a text editor and replace all utf8mb4 with utf8 and export after.\njust be critical to choose the right character set when exporting databases.</p>\n"
},
{
"answer_id": 198769,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress does not support MySQL 4 :</p>\n<blockquote>\n<p>To run WordPress your host just needs a couple of things:</p>\n<p>MySQL version <strong>5.0</strong> or greater (recommended: MySQL <strong>5.5</strong> or greater)</p>\n<p><a href=\"https://wordpress.org/about/requirements/\" rel=\"nofollow noreferrer\">https://wordpress.org/about/requirements/</a></p>\n</blockquote>\n<p>While the utf8mb4 encoding is recent change and you might work around it, <em>overall</em> you still need compatible MySQL version.</p>\n"
},
{
"answer_id": 206592,
"author": "Mike Castro Demaria",
"author_id": 49308,
"author_profile": "https://wordpress.stackexchange.com/users/49308",
"pm_score": 0,
"selected": false,
"text": "<p>From <a href=\"https://stackoverflow.com/questions/21911733/error-1115-42000-unknown-character-set-utf8mb4-in-mysql\">stackoverflow.com</a></p>\n\n<p>Your version does not support that character set, I believe it was 5.5.3 that introduced it. You should upgrade your mysql to the version you used to export this file.</p>\n\n<p>The error is then quite clear: you set a certain character set in your code, but your mysql version does not support it, and therefore does not know about it.</p>\n\n<p>According to <a href=\"https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html\" rel=\"nofollow noreferrer\">https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html</a> :</p>\n\n<blockquote>\n <p>utf8mb4 is a superset of utf8</p>\n</blockquote>\n\n<p>so maybe there is a chance you can just make it utf8, close your eyes and hope, but that would depend on your data, and I'd not recommend it.</p>\n"
}
] |
2015/06/29
|
[
"https://wordpress.stackexchange.com/questions/192944",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74540/"
] |
When I Import Mysql from local server to web ser it is showng me error
1115 - Unknown character set: 'utf8mb4' in Creating wordpress wp\_comment table
===============================================================================
```
CREATE TABLE IF NOT EXISTS `wp_commentmeta` (
//
//
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 AUTO_INCREMENT =1;
#1115 - Unknown character set: 'utf8mb4'
```
My mysql version is
```
Version information: 4.0.4, latest stable version: 4.4.10 (local version)
Version information: 4.0.10.7, latest stable version: 4.4.10( server version)
```
Please help me to solve out the error
|
WordPress does not support MySQL 4 :
>
> To run WordPress your host just needs a couple of things:
>
>
> MySQL version **5.0** or greater (recommended: MySQL **5.5** or greater)
>
>
> <https://wordpress.org/about/requirements/>
>
>
>
While the utf8mb4 encoding is recent change and you might work around it, *overall* you still need compatible MySQL version.
|
192,996 |
<p>I hope someone will help me:</p>
<p>I have a <strong>Custom Post Type</strong> (Movie) with its <strong>custom taxonomy</strong> (Producer), this taxonomy has its <strong>own terms</strong>, for example 'WarnerBros'.</p>
<p>How I can get all the posts of my term (WarnerBros)?</p>
<p>I have this but doesn't work yet.</p>
<pre><code>$args = array(
'post_type' => 'movie',
'tax_query' => array(
array(
'taxonomy' => 'producer',
'field' => 'slug',
'terms' => 'WarnerBros',
),
),
);
$query = new WP_Query( $args );
</code></pre>
<p>After playing with the code I resolved the problem, I will share my code for someone with the same issue:</p>
<p><pre>
$type = 'Movie'; // Custom Post Type Name
$tag = 'WarnerBros'; // Your Term</p>
<p>$args = array(
'post_type' => $type,
'paged' => $paged,
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
'tax_query'=>array(
array(
'taxonomy'=>'Producer', //Taxonomy Name
'field'=>'slug',
'terms'=>array($tag)
))
);</p>
<p>$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
if(is_object_in_term($post->ID,'Taxonomy_Name','Your_Term')) // Producer and WarnerBros { </p>
<code> echo '<div id="YourID">'; echo the_title(); echo '</div>';
} endwhile;
</code></pre>
<p></p>
|
[
{
"answer_id": 192999,
"author": "Iftieaq",
"author_id": 35653,
"author_profile": "https://wordpress.stackexchange.com/users/35653",
"pm_score": 1,
"selected": false,
"text": "<p>Try like this</p>\n\n<pre><code>$args = array(\n 'post_type' => 'movie',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'producer',\n 'field' => 'slug',\n 'terms' => 'WarnerBros',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>See more at <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\">wordpress codex</a></p>\n"
},
{
"answer_id": 193000,
"author": "marcovega",
"author_id": 14225,
"author_profile": "https://wordpress.stackexchange.com/users/14225",
"pm_score": 2,
"selected": false,
"text": "<p>This question has different answers in this specific Wordpress question, they may be of help:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/32902/display-all-posts-in-a-custom-post-type-grouped-by-a-custom-taxonomy\">Display all posts in a custom post type, grouped by a custom taxonomy</a></p>\n\n<p>Personally I used this method that worked for me just fine:</p>\n\n<pre><code>$terms = get_terms('tax_name');\n$posts = array();\nforeach ( $terms as $term ) {\n $posts[$term->name] = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'post_type', 'tax_name' => $term->name ));\n}\n</code></pre>\n\n<p>Editing it to your scenario this should work:</p>\n\n<pre><code>$terms = get_terms('producer');\n$posts = array();\nforeach ( $terms as $term ) {\n $posts[$term->name] = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'movie', 'tax_name' => $term->name ));\n}\n</code></pre>\n\n<p>Now you can get your posts:</p>\n\n<pre><code>print_r($posts[\"WarnerBros\"]);\n</code></pre>\n"
},
{
"answer_id": 286356,
"author": "Marcello B.",
"author_id": 100883,
"author_profile": "https://wordpress.stackexchange.com/users/100883",
"pm_score": 1,
"selected": false,
"text": "<p>Let's say that you have a custom post type <strong>plays</strong> and under the taxonomy <strong>genre</strong> you want to find all the posts with the category <strong>comedy</strong></p>\n\n<pre><code>$args = array(\n 'post_type' => 'plays', /*Post type (plays)*/\n 'tax_query' => array(\n array(\n 'taxonomy' => 'genre', /*Taxonomy to search (genre)*/\n 'field' => 'slug',\n 'terms' => 'comedy', /*Search category for (comedy)*/\n ),\n ),\n );\n $query = new WP_Query( $args );\n</code></pre>\n"
}
] |
2015/06/29
|
[
"https://wordpress.stackexchange.com/questions/192996",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73891/"
] |
I hope someone will help me:
I have a **Custom Post Type** (Movie) with its **custom taxonomy** (Producer), this taxonomy has its **own terms**, for example 'WarnerBros'.
How I can get all the posts of my term (WarnerBros)?
I have this but doesn't work yet.
```
$args = array(
'post_type' => 'movie',
'tax_query' => array(
array(
'taxonomy' => 'producer',
'field' => 'slug',
'terms' => 'WarnerBros',
),
),
);
$query = new WP_Query( $args );
```
After playing with the code I resolved the problem, I will share my code for someone with the same issue:
```
$type = 'Movie'; // Custom Post Type Name
$tag = 'WarnerBros'; // Your Term
```
$args = array(
'post\_type' => $type,
'paged' => $paged,
'posts\_per\_page' => -1,
'orderby' => 'menu\_order',
'order' => 'ASC',
'tax\_query'=>array(
array(
'taxonomy'=>'Producer', //Taxonomy Name
'field'=>'slug',
'terms'=>array($tag)
))
);
$loop = new WP\_Query( $args );
while ( $loop->have\_posts() ) : $loop->the\_post();
if(is\_object\_in\_term($post->ID,'Taxonomy\_Name','Your\_Term')) // Producer and WarnerBros {
`echo '<div id="YourID">'; echo the_title(); echo '</div>';
} endwhile;`
|
This question has different answers in this specific Wordpress question, they may be of help:
[Display all posts in a custom post type, grouped by a custom taxonomy](https://wordpress.stackexchange.com/questions/32902/display-all-posts-in-a-custom-post-type-grouped-by-a-custom-taxonomy)
Personally I used this method that worked for me just fine:
```
$terms = get_terms('tax_name');
$posts = array();
foreach ( $terms as $term ) {
$posts[$term->name] = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'post_type', 'tax_name' => $term->name ));
}
```
Editing it to your scenario this should work:
```
$terms = get_terms('producer');
$posts = array();
foreach ( $terms as $term ) {
$posts[$term->name] = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'movie', 'tax_name' => $term->name ));
}
```
Now you can get your posts:
```
print_r($posts["WarnerBros"]);
```
|
193,024 |
<p>I know there is an option to have the following code in the wp-config.php file:</p>
<pre><code>define('WP_DEFAULT_THEME', 'x-child-integrity-light');
define( 'TEMPLATEPATH', 'wp-content/themes/x');
</code></pre>
<p>I currently have this commented out and I'm trying to use the WP Replicator to replicate sites in a multisite install. I'd like to have the code automatically activate the child theme when it's installing the new site. By default, it's making the Twenty Fifteen theme active. How can I go about doing this?</p>
|
[
{
"answer_id": 193025,
"author": "Karun",
"author_id": 63470,
"author_profile": "https://wordpress.stackexchange.com/users/63470",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <code>switch_theme</code> function</p>\n\n<pre><code><?php switch_theme( $stylesheet ) ?>\n</code></pre>\n\n<p><code>$stylesheet</code> is the Stylesheet name.</p>\n"
},
{
"answer_id": 193029,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": true,
"text": "<p>Use <code>switch_theme</code> as already indicated in another answer, but hook it to <code>wpmu_new_blog</code></p>\n\n<blockquote>\n <p>This function runs when a user self-registers a new site as well as when a super admin creates a new site. hook to 'wpmu_new_blog' for events that should affect all new sites.</p>\n \n <p><a href=\"https://codex.wordpress.org/function_reference/wpmu_create_blog\" rel=\"nofollow\">https://codex.wordpress.org/function_reference/wpmu_create_blog</a></p>\n</blockquote>\n\n<p>If not the code will run constantly, which will be inefficient and make switching themes impossible ( or unpredictable ).</p>\n\n<p>In other words:</p>\n\n<pre><code>function default_theme_wpse_193024() {\n switch_theme('twentythirteen');\n}\nadd_action('wpmu_new_blog','default_theme_wpse_193024');\n</code></pre>\n\n<p>For <code>switch_theme()</code>, despite the parameter being named somewhat inexplicably \"stylesheet\", use the name of the theme folder. <a href=\"https://codex.wordpress.org/Function_Reference/switch_theme\" rel=\"nofollow\">Per the Codex</a>: </p>\n\n<blockquote>\n <p>Accepts one argument: $stylesheet of the theme. ($stylesheet is the\n name of your folder slug. It's the same value that you'd use for a\n child theme, something like <code>twentythirteen</code>.)</p>\n</blockquote>\n"
}
] |
2015/06/30
|
[
"https://wordpress.stackexchange.com/questions/193024",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13472/"
] |
I know there is an option to have the following code in the wp-config.php file:
```
define('WP_DEFAULT_THEME', 'x-child-integrity-light');
define( 'TEMPLATEPATH', 'wp-content/themes/x');
```
I currently have this commented out and I'm trying to use the WP Replicator to replicate sites in a multisite install. I'd like to have the code automatically activate the child theme when it's installing the new site. By default, it's making the Twenty Fifteen theme active. How can I go about doing this?
|
Use `switch_theme` as already indicated in another answer, but hook it to `wpmu_new_blog`
>
> This function runs when a user self-registers a new site as well as when a super admin creates a new site. hook to 'wpmu\_new\_blog' for events that should affect all new sites.
>
>
> <https://codex.wordpress.org/function_reference/wpmu_create_blog>
>
>
>
If not the code will run constantly, which will be inefficient and make switching themes impossible ( or unpredictable ).
In other words:
```
function default_theme_wpse_193024() {
switch_theme('twentythirteen');
}
add_action('wpmu_new_blog','default_theme_wpse_193024');
```
For `switch_theme()`, despite the parameter being named somewhat inexplicably "stylesheet", use the name of the theme folder. [Per the Codex](https://codex.wordpress.org/Function_Reference/switch_theme):
>
> Accepts one argument: $stylesheet of the theme. ($stylesheet is the
> name of your folder slug. It's the same value that you'd use for a
> child theme, something like `twentythirteen`.)
>
>
>
|
193,076 |
<p>i use a <a href="http://www.broobe.com/wordpress-plugins/wp-jquery-timelinr/" rel="nofollow">plugin</a> that containing this code and i want to change js location to be located in my template directory instead of plugin without editing the plugin files</p>
<pre><code>class jqueryTimelinrLoad {
public function registerScripts()
{
if (!wp_script_is( 'jquery', 'registered' )) wp_register_script( 'jquery' );
wp_deregister_script('jquery.timelinr');
wp_register_script('jquery.timelinr', JQTL_BASE_URL . '/assets/js/jquery.timelinr-1.0.js', array( 'jquery' ));
}
public function loadScripts() {
if (!is_admin()) {
if (!wp_script_is( 'jquery', 'queue' )) wp_enqueue_script( 'jquery' );
wp_enqueue_script('jquery.timelinr', JQTL_BASE_URL . '/assets/js/jquery.timelinr-1.0.js', array( 'jquery' ));
}
}
}
</code></pre>
<p>i try this and it add the new link but old link also still</p>
<pre><code>function drw_timeline_js () {
$result = $GLOBALS["jqueryTimelinrLoad"]->loadScripts();
wp_dequeue_script('jquery.timelinr');
wp_deregister_script( 'jquery.timelinr');
wp_enqueue_script('jquery.timelinr2', get_template_directory_uri() . '/js/jquery.timelinr-1.0.js', array( 'jquery' ));
return $result;
}
add_action('init', 'drw_timeline_js', 1);
</code></pre>
|
[
{
"answer_id": 193077,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": false,
"text": "<p>If <code>loadScripts()</code> is registered/enqueued correctly (the code posted doesn't show the hook used) then is it enqueued on <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow\"><code>wp_enqueue_scripts</code> which runs well after <code>init</code></a> so what you are doing is trying to remove something that hasn't been added yet, and will be added later. Assuming that:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'drw_timeline_js', PHP_INT_MAX);\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/reserved.constants.php\" rel=\"nofollow\"><code>PHP_INT_MAX</code></a> will ensure that your code runs last on that hook.</p>\n\n<p>I also don't see the reason,or the need for, the <code>$result = $GLOBALS[\"jqueryTimelinrLoad\"]->loadScripts();</code> line or for the <code>return</code> line in your function.</p>\n"
},
{
"answer_id": 193080,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>Scripts should be enqueued on <code>wp_enqueue_scripts</code> action hook, which runs after <code>init</code> action. So dequeuing on <code>init</code> won't work because sripts are not enqueued yet. Before enqueued scripts are printed, <code>wp_print_scripts</code> action is triggered so you can dequeue or unregister scripts safely at this moment:</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'drw_timelinr_dequeue' );\nfunction drw_timelinr_dequeue () {\n\n wp_dequeue_script('jquery.timelinr');\n\n}\n\nadd_action('wp_enqueue_scripts', 'drw_timeline_js');\nfunction drw_timeline_js () {\n\n wp_enqueue_script('jquery.timelinr2', get_template_directory_uri() . '/js/jquery.timelinr-1.0.js', array( 'jquery' ));\n\n\n}\n</code></pre>\n"
}
] |
2015/06/30
|
[
"https://wordpress.stackexchange.com/questions/193076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75112/"
] |
i use a [plugin](http://www.broobe.com/wordpress-plugins/wp-jquery-timelinr/) that containing this code and i want to change js location to be located in my template directory instead of plugin without editing the plugin files
```
class jqueryTimelinrLoad {
public function registerScripts()
{
if (!wp_script_is( 'jquery', 'registered' )) wp_register_script( 'jquery' );
wp_deregister_script('jquery.timelinr');
wp_register_script('jquery.timelinr', JQTL_BASE_URL . '/assets/js/jquery.timelinr-1.0.js', array( 'jquery' ));
}
public function loadScripts() {
if (!is_admin()) {
if (!wp_script_is( 'jquery', 'queue' )) wp_enqueue_script( 'jquery' );
wp_enqueue_script('jquery.timelinr', JQTL_BASE_URL . '/assets/js/jquery.timelinr-1.0.js', array( 'jquery' ));
}
}
}
```
i try this and it add the new link but old link also still
```
function drw_timeline_js () {
$result = $GLOBALS["jqueryTimelinrLoad"]->loadScripts();
wp_dequeue_script('jquery.timelinr');
wp_deregister_script( 'jquery.timelinr');
wp_enqueue_script('jquery.timelinr2', get_template_directory_uri() . '/js/jquery.timelinr-1.0.js', array( 'jquery' ));
return $result;
}
add_action('init', 'drw_timeline_js', 1);
```
|
Scripts should be enqueued on `wp_enqueue_scripts` action hook, which runs after `init` action. So dequeuing on `init` won't work because sripts are not enqueued yet. Before enqueued scripts are printed, `wp_print_scripts` action is triggered so you can dequeue or unregister scripts safely at this moment:
```
add_action( 'wp_print_scripts', 'drw_timelinr_dequeue' );
function drw_timelinr_dequeue () {
wp_dequeue_script('jquery.timelinr');
}
add_action('wp_enqueue_scripts', 'drw_timeline_js');
function drw_timeline_js () {
wp_enqueue_script('jquery.timelinr2', get_template_directory_uri() . '/js/jquery.timelinr-1.0.js', array( 'jquery' ));
}
```
|
193,084 |
<p><a href="http://wp-cli.org/" rel="noreferrer">wp-cli</a> is great. But it's not clear how I can quickly change a user password with it.</p>
<p><a href="https://wordpress.stackexchange.com/questions/9919/how-to-change-a-users-password-programatically">How to change a user's password programatically</a> can probably help to figure this out.</p>
<p>Although <code>wp user update username --field=password</code> is not gonna cut it, apparently <code>md5</code> is deprecated so it should go through <a href="http://queryposts.com/function/wp_set_password/" rel="noreferrer"><code>wp_set_password</code></a>.</p>
|
[
{
"answer_id": 193085,
"author": "the",
"author_id": 44793,
"author_profile": "https://wordpress.stackexchange.com/users/44793",
"pm_score": 7,
"selected": true,
"text": "<p>This does the trick:</p>\n\n<pre><code>wp user update USERNAME --user_pass=\"PASSWORD\"\n</code></pre>\n\n<p>(Found it <a href=\"https://github.com/wp-cli/wp-cli/issues/1809\" rel=\"noreferrer\">here</a>.)</p>\n"
},
{
"answer_id": 240889,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>Just to append one minor thing; sometimes the password may start with the = character. I prefer using this notation, just because of that.</p>\n\n<pre><code>wp user update USERNAME --user_pass=\"PASSWORD\"\n</code></pre>\n"
},
{
"answer_id": 327890,
"author": "alo Malbarez",
"author_id": 62765,
"author_profile": "https://wordpress.stackexchange.com/users/62765",
"pm_score": 4,
"selected": false,
"text": "<p>first check the user name:</p>\n\n<pre><code>wp user list\n</code></pre>\n\n<p>then change password without leaving traces in history</p>\n\n<pre><code>wp user update admin --prompt=user_pass\n</code></pre>\n"
},
{
"answer_id": 369056,
"author": "Ricardo Bolivia",
"author_id": 190032,
"author_profile": "https://wordpress.stackexchange.com/users/190032",
"pm_score": 0,
"selected": false,
"text": "<p>I have found that sudo definitely changes the path, so I have tried using --allow-root without sudo and the commands work</p>\n"
}
] |
2015/06/30
|
[
"https://wordpress.stackexchange.com/questions/193084",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44793/"
] |
[wp-cli](http://wp-cli.org/) is great. But it's not clear how I can quickly change a user password with it.
[How to change a user's password programatically](https://wordpress.stackexchange.com/questions/9919/how-to-change-a-users-password-programatically) can probably help to figure this out.
Although `wp user update username --field=password` is not gonna cut it, apparently `md5` is deprecated so it should go through [`wp_set_password`](http://queryposts.com/function/wp_set_password/).
|
This does the trick:
```
wp user update USERNAME --user_pass="PASSWORD"
```
(Found it [here](https://github.com/wp-cli/wp-cli/issues/1809).)
|
193,086 |
<p>I am using wordpress functions in a custom php file including <code>wp-load.php</code>, run from browser it is fine, but run from command line with <code>php /path/.php</code> <code>wp-load.php</code> causes problems:</p>
<pre><code>Warning: Cannot modify header information - headers already sent in /../wp-includes/ms-settings.php on line 162
</code></pre>
<p>code example to reproduce:</p>
<pre><code>echo 'something';
require "/../wp-load.php";
</code></pre>
|
[
{
"answer_id": 193139,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 2,
"selected": true,
"text": "<p>WordPress has a command line library called <a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a>. You can extend it to create your own commands. I would recommend this for any work on the command line.</p>\n"
},
{
"answer_id": 193213,
"author": "untore",
"author_id": 49220,
"author_profile": "https://wordpress.stackexchange.com/users/49220",
"pm_score": 0,
"selected": false,
"text": "<p>I resolved this by using another php file to use from the command line with just a line like this:</p>\n\n<p><code>file_get_contents('url to file I want to run');</code></p>\n\n<p>the problem with using wordpress function in files outside of wordpress is that wordpress is bound to its installation so you gotta run it from an url belonging to the wordpress setup I think</p>\n"
}
] |
2015/06/30
|
[
"https://wordpress.stackexchange.com/questions/193086",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49220/"
] |
I am using wordpress functions in a custom php file including `wp-load.php`, run from browser it is fine, but run from command line with `php /path/.php` `wp-load.php` causes problems:
```
Warning: Cannot modify header information - headers already sent in /../wp-includes/ms-settings.php on line 162
```
code example to reproduce:
```
echo 'something';
require "/../wp-load.php";
```
|
WordPress has a command line library called [WP-CLI](http://wp-cli.org/). You can extend it to create your own commands. I would recommend this for any work on the command line.
|
193,089 |
<p>I am trying to change the path to my uploads directory when on this one specific page in my custom plugin. The page is a standard php page and not any specific type of post type page.</p>
<p>I have found numerous articles explaining the process, and I can see how it would work if this were a custom post type, but seeing as it's not the examples are not working as intended.</p>
<p>The URL to my custom page is as follows:
<code>http://localhost/custom-plugin/wp-admin/admin.php?page=custom-plugin-page&id=1</code>. </p>
<p>the $_POST variable is dynamic based on the item that the user is editing.</p>
<p>I have come across the following and adjusted it to my needs:</p>
<pre><code>function edd_load_upload_filter() {
global $pagenow;
if ( ! empty( $_POST['page'] ) && $_POST['page'] == 'custom-plugin-page' && ( 'async-upload.php' == $pagenow || 'media-upload.php' == $pagenow ) ) {
add_filter( 'upload_dir', 'edd_set_upload_dir' );
}
}
add_action('admin_init', 'edd_load_upload_filter');
function edd_set_upload_dir($upload) {
$upload['subdir'] = '/edd' . $upload['subdir'];
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
</code></pre>
<p>But as you can see, the function is checking if the post type is type 'download'.</p>
<p>From what I can tell, the $_POST variable is not empty on initial page load, but when the media modal is opened it is empty. Since it returns as empty inside the media modal, the path to the upload directory does not properly get set. If I remove the <code>!empty( $_POST[
page'] );</code> check the path is properly adjusted, but then it gets adjusted across the entire site and not just on my custom page.</p>
<p>Not sure why the examples on the net all use some $_POST or $_REQUEST variable, but when I go to use it, it is empty so my function never fires. Any ideas?</p>
|
[
{
"answer_id": 193102,
"author": "EHerman",
"author_id": 43000,
"author_profile": "https://wordpress.stackexchange.com/users/43000",
"pm_score": 3,
"selected": true,
"text": "<p>After working on this for a bit and checking the GLOBALS variable for anything useful, it looks like the referring URL inside of the media modal is the same URL as my custom plugin page.</p>\n\n<p>Using that and splitting it up a bit I was able to confirm that I am on the approrpriate page. I'm sure that there are other, more elegant solutions out there, but this is what I was able to come up with. I have tested and it seems to be working properly.</p>\n\n<p>Here is my final solution :</p>\n\n<pre><code> add_filter( 'admin_init' , 'check_if_we_should_change_upload_dir', 999 );\n function check_if_we_should_change_upload_dir() { \n global $pagenow;\n $referrer = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '';\n if( $referrer != '' ) {\n $explode_1 = explode( 'page=' , $referrer );\n if( isset( $explode_1[1] ) ) {\n $referring_page = explode( '&id=' , $explode_1[1] );\n if( isset( $referring_page[0] ) && $referring_page[0] == 'custom-plugin-page' && ( 'async-upload.php' == $pagenow || 'media-upload.php' == $pagenow ) ) {\n add_filter( 'upload_dir', 'alter_the_upload_dir' );\n }\n }\n }\n }\n\n\n function alter_the_upload_dir( $upload ) {\n $upload['subdir'] = '/custom-directory' . $upload['subdir'];\n $upload['path'] = $upload['basedir'] . $upload['subdir'];\n $upload['url'] = $upload['baseurl'] . $upload['subdir'];\n return $upload;\n }\n</code></pre>\n\n<p>If anyone has any better solutions to checking, I am all ears!</p>\n\n<p>Evan</p>\n"
},
{
"answer_id": 193184,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks EHerman for your solution. My simplified version of your script would use the HTTP_REFERER in the upload filter directly:</p>\n\n<pre><code>function my_custom_upload_dir($path) {\n\n if(isset( $_SERVER['HTTP_REFERER'] )) {\n //parse url into array\n $referrer = parse_url($_SERVER['HTTP_REFERER']);\n $queries;\n // take the query part and parse it into array\n parse_str($referrer['query'], $queries);\n\n // check for anything that was in the query string of the current screen\n // you can use what ever you see in the wp-admin url before the upload frame opens \n if( isset($queries['taxonomy']) ) {\n\n $mydir = '/taxonomy-files';\n\n $path['subdir'] = $mydir;\n $path['path'] = $path['basedir'].$mydir; \n $path['url'] = $path['baseurl'].$mydir; \n }\n }\n\n return $path; //altered or not\n}\n</code></pre>\n\n<p>And to use the filter correctly</p>\n\n<pre><code>add_filter('wp_handle_upload_prefilter', 'my_upload_prefilter');\nadd_filter('wp_handle_upload', 'my_handle_upload');\n\nfunction my_upload_prefilter( $file ) {\n add_filter('upload_dir', 'my_custom_upload_dir');\n return $file;\n}\n\nfunction my_handle_upload( $fileinfo ) {\n remove_filter('upload_dir', 'my_custom_upload_dir');\n return $fileinfo;\n} \n</code></pre>\n"
}
] |
2015/06/30
|
[
"https://wordpress.stackexchange.com/questions/193089",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43000/"
] |
I am trying to change the path to my uploads directory when on this one specific page in my custom plugin. The page is a standard php page and not any specific type of post type page.
I have found numerous articles explaining the process, and I can see how it would work if this were a custom post type, but seeing as it's not the examples are not working as intended.
The URL to my custom page is as follows:
`http://localhost/custom-plugin/wp-admin/admin.php?page=custom-plugin-page&id=1`.
the $\_POST variable is dynamic based on the item that the user is editing.
I have come across the following and adjusted it to my needs:
```
function edd_load_upload_filter() {
global $pagenow;
if ( ! empty( $_POST['page'] ) && $_POST['page'] == 'custom-plugin-page' && ( 'async-upload.php' == $pagenow || 'media-upload.php' == $pagenow ) ) {
add_filter( 'upload_dir', 'edd_set_upload_dir' );
}
}
add_action('admin_init', 'edd_load_upload_filter');
function edd_set_upload_dir($upload) {
$upload['subdir'] = '/edd' . $upload['subdir'];
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
```
But as you can see, the function is checking if the post type is type 'download'.
From what I can tell, the $\_POST variable is not empty on initial page load, but when the media modal is opened it is empty. Since it returns as empty inside the media modal, the path to the upload directory does not properly get set. If I remove the `!empty( $_POST[
page'] );` check the path is properly adjusted, but then it gets adjusted across the entire site and not just on my custom page.
Not sure why the examples on the net all use some $\_POST or $\_REQUEST variable, but when I go to use it, it is empty so my function never fires. Any ideas?
|
After working on this for a bit and checking the GLOBALS variable for anything useful, it looks like the referring URL inside of the media modal is the same URL as my custom plugin page.
Using that and splitting it up a bit I was able to confirm that I am on the approrpriate page. I'm sure that there are other, more elegant solutions out there, but this is what I was able to come up with. I have tested and it seems to be working properly.
Here is my final solution :
```
add_filter( 'admin_init' , 'check_if_we_should_change_upload_dir', 999 );
function check_if_we_should_change_upload_dir() {
global $pagenow;
$referrer = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '';
if( $referrer != '' ) {
$explode_1 = explode( 'page=' , $referrer );
if( isset( $explode_1[1] ) ) {
$referring_page = explode( '&id=' , $explode_1[1] );
if( isset( $referring_page[0] ) && $referring_page[0] == 'custom-plugin-page' && ( 'async-upload.php' == $pagenow || 'media-upload.php' == $pagenow ) ) {
add_filter( 'upload_dir', 'alter_the_upload_dir' );
}
}
}
}
function alter_the_upload_dir( $upload ) {
$upload['subdir'] = '/custom-directory' . $upload['subdir'];
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
```
If anyone has any better solutions to checking, I am all ears!
Evan
|
193,095 |
<p>I'm looking to edit my theme layout of the <em>aside</em> post format.</p>
<p>I have already included the <code>add_theme_support()</code> function to include the aside option when creating a post. However, the layout of an <em>aside</em> does not look good. I wish to style it pretty much identically to the <em>video</em> format.</p>
<p>Which file in my theme represents the <em>aside</em> post format layout?</p>
|
[
{
"answer_id": 212261,
"author": "Madivad",
"author_id": 37314,
"author_profile": "https://wordpress.stackexchange.com/users/37314",
"pm_score": 1,
"selected": false,
"text": "<p>Mostly you would just make CSS changes. For example, a post that has the <code>aside</code> format will have included in it's mark-up a class of <code>format-aside</code> which you could override in your own CSS, whether it be by way of child theme support or CSS plugin.</p>\n<p>I've only just been playing with this today (incidentally, which is how I came across this question).</p>\n<p><strong>Example:</strong>\nYou could hide the title of posts tagged with the <code>quote</code> post-format (ie <code>format-quote</code>) by including this in your CSS file:</p>\n<pre><code>.home .format-quote .entry-title {\n display: none;\n}\n</code></pre>\n<p>This would then format that entry on your blog page / index to not include the title from the post, and would make the quote just appear as more of an inline quote between two posts.</p>\n<p>Or you could include a background image or custom colour behind the post based on the format.</p>\n<p>I haven't completed it yet, but I'm working on a format to use the post title as the author of a quote, and the content to be the quote content, and the position the title under the quote in smaller than <code><h2></code> tags, or possibly just add an <code>::after</code> element to maybe include the word "says" or "said" so that the quote field could be presented thus:</p>\n<blockquote>\n<h2>Isaac Newton said:</h2>\n<p>I can calculate the motion of heavenly bodies, but not the madness of people.</p>\n</blockquote>\n<p>There isn't a plethora of information out there, but here are a couple of links which go into a little further detail (the first being WordPress Codex):</p>\n<p><a href=\"https://codex.wordpress.org/User:Chipbennett/Post_Formats\" rel=\"nofollow noreferrer\">WordPress Codex page on Post Formats</a><br />\n<a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-wordpress-post-formats\" rel=\"nofollow noreferrer\">Elegant Themes Blog post: Creating Post Formats</a></p>\n"
},
{
"answer_id": 212265,
"author": "Fenris",
"author_id": 85543,
"author_profile": "https://wordpress.stackexchange.com/users/85543",
"pm_score": 1,
"selected": false,
"text": "<p>You could edit some code in <code>single.php</code> file by using <code>get_post_format()</code> function to check your post format and show anything you want to show for each post format.</p>\n\n<p>For example:</p>\n\n<pre><code>if ( get_post_format( get_the_ID() ) == 'aside' ) {\n // Show something different from another template here!!!\n}\n</code></pre>\n"
},
{
"answer_id": 260787,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 0,
"selected": false,
"text": "<p>Create a template part for it named <code>content-aside.php</code> and use a conditional in <code>single.php</code> to call it:</p>\n\n<pre><code>if ( is_singular( 'aside' ) ) {\n get_template_part( 'content', 'aside');\n} else {\n get_template_part( 'content', 'single');\n}\n</code></pre>\n\n<p>A simple <code>get_template_part()</code> may do it too:</p>\n\n<pre><code> if ( is_singular() ) {\n get_template_part( 'content', get_post_type() );\n }\n</code></pre>\n"
}
] |
2015/06/30
|
[
"https://wordpress.stackexchange.com/questions/193095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58657/"
] |
I'm looking to edit my theme layout of the *aside* post format.
I have already included the `add_theme_support()` function to include the aside option when creating a post. However, the layout of an *aside* does not look good. I wish to style it pretty much identically to the *video* format.
Which file in my theme represents the *aside* post format layout?
|
Mostly you would just make CSS changes. For example, a post that has the `aside` format will have included in it's mark-up a class of `format-aside` which you could override in your own CSS, whether it be by way of child theme support or CSS plugin.
I've only just been playing with this today (incidentally, which is how I came across this question).
**Example:**
You could hide the title of posts tagged with the `quote` post-format (ie `format-quote`) by including this in your CSS file:
```
.home .format-quote .entry-title {
display: none;
}
```
This would then format that entry on your blog page / index to not include the title from the post, and would make the quote just appear as more of an inline quote between two posts.
Or you could include a background image or custom colour behind the post based on the format.
I haven't completed it yet, but I'm working on a format to use the post title as the author of a quote, and the content to be the quote content, and the position the title under the quote in smaller than `<h2>` tags, or possibly just add an `::after` element to maybe include the word "says" or "said" so that the quote field could be presented thus:
>
> Isaac Newton said:
> ------------------
>
>
> I can calculate the motion of heavenly bodies, but not the madness of people.
>
>
>
There isn't a plethora of information out there, but here are a couple of links which go into a little further detail (the first being WordPress Codex):
[WordPress Codex page on Post Formats](https://codex.wordpress.org/User:Chipbennett/Post_Formats)
[Elegant Themes Blog post: Creating Post Formats](https://www.elegantthemes.com/blog/tips-tricks/how-to-create-wordpress-post-formats)
|
193,110 |
<p>I have the following bit of code:</p>
<pre><code>$args = array(
'posts_per_page' => -1,
'category' => 7,
'orderby' => 'name',
'order' => 'ASC',
'post_type' => 'product'
);
$posts = get_posts($args);var_dump($posts);
</code></pre>
<p>This should return one post I know that is in the category, but it isn't. If I leave out the 'category'-argument, I get all the products, so I know this should normally work. If I change the category to 1 and take out my custom post type (product), I get my default posts. </p>
<p>I can't see what's wrong with this. Can anyone spot what the problem is?</p>
|
[
{
"answer_id": 193145,
"author": "Rohit Gilbile",
"author_id": 75488,
"author_profile": "https://wordpress.stackexchange.com/users/75488",
"pm_score": 3,
"selected": false,
"text": "<pre><code><ul>\n <?php\n $args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );\n\n $myposts = get_posts( $args );\n foreach ( $myposts as $post ) : setup_postdata( $post ); ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n <?php endforeach; \n wp_reset_postdata();?>\n\n\n </ul>\n</code></pre>\n\n<p>May <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"noreferrer\">this will</a> help You.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 193155,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 6,
"selected": true,
"text": "<p>In all probability you are using a custom taxonomy, and not the build-in <code>category</code> taxonomy. If this is the case, then the category parameters won't work. You will need a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"noreferrer\"><code>tax_query</code></a> to query posts from a specific term. (<em>Remember, <code>get_posts</code> uses <code>WP_Query</code>, so you can pass any parameter from <code>WP_Query</code> to <code>get_posts</code></em>)</p>\n\n<pre><code>$args = [\n 'post_type' => 'product',\n 'tax_query' => [\n [\n 'taxonomy' => 'my_custom_taxonomy',\n 'terms' => 7,\n 'include_children' => false // Remove if you need posts from term 7 child terms\n ],\n ],\n // Rest of your arguments\n];\n</code></pre>\n\n<h2>ADDITIONAL RESOURCES</h2>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/a/158223/31545\">What is the difference between custom taxonomies and categories</a></li>\n</ul>\n"
}
] |
2015/06/30
|
[
"https://wordpress.stackexchange.com/questions/193110",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9243/"
] |
I have the following bit of code:
```
$args = array(
'posts_per_page' => -1,
'category' => 7,
'orderby' => 'name',
'order' => 'ASC',
'post_type' => 'product'
);
$posts = get_posts($args);var_dump($posts);
```
This should return one post I know that is in the category, but it isn't. If I leave out the 'category'-argument, I get all the products, so I know this should normally work. If I change the category to 1 and take out my custom post type (product), I get my default posts.
I can't see what's wrong with this. Can anyone spot what the problem is?
|
In all probability you are using a custom taxonomy, and not the build-in `category` taxonomy. If this is the case, then the category parameters won't work. You will need a [`tax_query`](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) to query posts from a specific term. (*Remember, `get_posts` uses `WP_Query`, so you can pass any parameter from `WP_Query` to `get_posts`*)
```
$args = [
'post_type' => 'product',
'tax_query' => [
[
'taxonomy' => 'my_custom_taxonomy',
'terms' => 7,
'include_children' => false // Remove if you need posts from term 7 child terms
],
],
// Rest of your arguments
];
```
ADDITIONAL RESOURCES
--------------------
* [What is the difference between custom taxonomies and categories](https://wordpress.stackexchange.com/a/158223/31545)
|
193,122 |
<p>I read that <code>get_template_part()</code> should only used by themes not plugins, I don't know if using it inside a widget function (created by the theme) is considered as a plugin or not.</p>
<p>Anyway, I'm trying to pass that widget variables ($myvar) to the template ('loop.php' in my case), but it doesn't fetch it even with using <code>global $myvar;</code> inside the template.</p>
<p>Here's my widget function code:</p>
<pre><code>function widget($args, $instance) {
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
if ($title) { echo $before_title.$title.$after_title; }
$myvar = 'start';
get_template_part('loop'); ?>
echo $after_widget;
}
</code></pre>
|
[
{
"answer_id": 193124,
"author": "gdaniel",
"author_id": 30984,
"author_profile": "https://wordpress.stackexchange.com/users/30984",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>set_query_var('myvarname', $myvarvalue);</code> before <code>get_template_part()</code>. Then in your loop template you can access the var using <code>$myvarname</code>.</p>\n\n<p>You can also skip all that and use <a href=\"https://codex.wordpress.org/Function_Reference/locate_template\" rel=\"nofollow\">locate template</a> instead.</p>\n"
},
{
"answer_id": 280760,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Indeed, <code>get_template_part</code> is meant to be used in themes only, though that would include widgets inside your theme. <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">Looking at the source code</a> of the function you'll see that the main reason for this is that <code>get_template_part</code> does some extra theme related stuff before it calls <code>locate_template</code> in a non-default way.</p>\n\n<p>That said you should have no problem calling it from a widget, so the issue most likely is that your <code>loop.php</code> is not in the place where WP is looking for it.</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part?rq=1\">Refer to this answer</a> for passing a variable to a template.</p>\n"
}
] |
2015/06/30
|
[
"https://wordpress.stackexchange.com/questions/193122",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37529/"
] |
I read that `get_template_part()` should only used by themes not plugins, I don't know if using it inside a widget function (created by the theme) is considered as a plugin or not.
Anyway, I'm trying to pass that widget variables ($myvar) to the template ('loop.php' in my case), but it doesn't fetch it even with using `global $myvar;` inside the template.
Here's my widget function code:
```
function widget($args, $instance) {
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
if ($title) { echo $before_title.$title.$after_title; }
$myvar = 'start';
get_template_part('loop'); ?>
echo $after_widget;
}
```
|
Indeed, `get_template_part` is meant to be used in themes only, though that would include widgets inside your theme. [Looking at the source code](https://developer.wordpress.org/reference/functions/get_template_part/) of the function you'll see that the main reason for this is that `get_template_part` does some extra theme related stuff before it calls `locate_template` in a non-default way.
That said you should have no problem calling it from a widget, so the issue most likely is that your `loop.php` is not in the place where WP is looking for it.
[Refer to this answer](https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part?rq=1) for passing a variable to a template.
|
193,166 |
<p>I am customizing this theme . I am using <code>get_the_gallery()</code> function to get the gallery from the custom post . I am able to do so, but when the gallery is inserted between the shortcodes...</p>
<p>For eg:</p>
<pre><code>[two-third]
[gallery ids="18,17,8,7,6"]
[/two-third]
</code></pre>
<p>then i am not able to get the gallery..I am using the following code</p>
<pre><code><?php
if ( get_post_gallery() ):
$gallery = get_post_gallery( $post, false );
$w3_ids = explode( ",", $gallery['ids'] );
?>
<?php
$gallery_count=1;
foreach( $w3_ids AS $w3_id ):
$src = wp_get_attachment_image_src($w3_id,'full');
?>
<div class="item <?php if($gallery_count==1)echo "active"; ?>">
<img src="<?php echo $src[0]; ?>" alt="" />
</div>
<?php
$gallery_count++;
endforeach;
endif;
?>
</code></pre>
<p>What can be done... Please help</p>
|
[
{
"answer_id": 193180,
"author": "Mak",
"author_id": 75502,
"author_profile": "https://wordpress.stackexchange.com/users/75502",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php\n $id=the_ID();\n $gallery_count = $wpdb->get_var(\"SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' && ID=$id\");\n echo $gallery_count;\n?>\n</code></pre>\n\n<p>I think...!!! Try this for Particular gallery.</p>\n"
},
{
"answer_id": 193187,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 2,
"selected": true,
"text": "<p>I don't know why the code is not working.\nBut this is how i did this may be helpful for some noob like me</p>\n\n<pre><code><?php \n $name = get_the_content(); \n preg_match('/\\[gallery ids=\"([^]]*)\\\"]/', $name, $match); \n $w3_ids = explode( \",\", $match[1] ); \n $gallery_count=1;\n foreach( $w3_ids AS $w3_id ): \n $src = wp_get_attachment_image_src($w3_id,'full'); \n?> \n <div class=\"item <?php if($gallery_count==1)echo \"active\"; ?>\">\n <img src=\"<?php echo $src[0]; ?>\" alt=\"\" />\n </div>\n<?php \n $gallery_count++;\n endforeach; \n?>\n</code></pre>\n"
}
] |
2015/07/01
|
[
"https://wordpress.stackexchange.com/questions/193166",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55034/"
] |
I am customizing this theme . I am using `get_the_gallery()` function to get the gallery from the custom post . I am able to do so, but when the gallery is inserted between the shortcodes...
For eg:
```
[two-third]
[gallery ids="18,17,8,7,6"]
[/two-third]
```
then i am not able to get the gallery..I am using the following code
```
<?php
if ( get_post_gallery() ):
$gallery = get_post_gallery( $post, false );
$w3_ids = explode( ",", $gallery['ids'] );
?>
<?php
$gallery_count=1;
foreach( $w3_ids AS $w3_id ):
$src = wp_get_attachment_image_src($w3_id,'full');
?>
<div class="item <?php if($gallery_count==1)echo "active"; ?>">
<img src="<?php echo $src[0]; ?>" alt="" />
</div>
<?php
$gallery_count++;
endforeach;
endif;
?>
```
What can be done... Please help
|
I don't know why the code is not working.
But this is how i did this may be helpful for some noob like me
```
<?php
$name = get_the_content();
preg_match('/\[gallery ids="([^]]*)\"]/', $name, $match);
$w3_ids = explode( ",", $match[1] );
$gallery_count=1;
foreach( $w3_ids AS $w3_id ):
$src = wp_get_attachment_image_src($w3_id,'full');
?>
<div class="item <?php if($gallery_count==1)echo "active"; ?>">
<img src="<?php echo $src[0]; ?>" alt="" />
</div>
<?php
$gallery_count++;
endforeach;
?>
```
|
193,182 |
<p>My admin panel is very slow I've tried to debug the issue. I nailed it to the function <code>wp_remote_post</code> and an internal error message thrown by curl on this line</p>
<pre><code>return new WP_Error( 'http_request_failed', curl_error( $handle ) );
</code></pre>
<p>I wonder what would have happened if I uninstalled curl. Can WordPress use other mechanisms to make http requests or is curl required?</p>
|
[
{
"answer_id": 193185,
"author": "Jimtrim",
"author_id": 59213,
"author_profile": "https://wordpress.stackexchange.com/users/59213",
"pm_score": 0,
"selected": false,
"text": "<p>Wordpress themselfes claim to not require anything else than: </p>\n\n<ul>\n<li>Nginx or Apace .</li>\n<li>PHP 5.2.4 or greater.</li>\n<li>MySQL or some other database that connects to PHP's <code>mysqli_connect(...)</code>, like MariaDB.</li>\n<li>Some way to rewrite requests like Apache mod_rewrite.</li>\n</ul>\n\n<p>No requirements for curl is mentioned, so I would assume that it will use other methods if curl is not avaible.</p>\n\n<p>Refrence: <a href=\"https://wordpress.org/about/requirements/\" rel=\"nofollow\">https://wordpress.org/about/requirements/</a></p>\n"
},
{
"answer_id": 193384,
"author": "Gregor",
"author_id": 74519,
"author_profile": "https://wordpress.stackexchange.com/users/74519",
"pm_score": 1,
"selected": false,
"text": "<p>For the record, I have uninstalled curl and wordpress was working on seamlessly.</p>\n<p>So I confirm that curl is not a dependency of wordpress.</p>\n<p>However, some plugins may require curl.</p>\n"
}
] |
2015/07/01
|
[
"https://wordpress.stackexchange.com/questions/193182",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74519/"
] |
My admin panel is very slow I've tried to debug the issue. I nailed it to the function `wp_remote_post` and an internal error message thrown by curl on this line
```
return new WP_Error( 'http_request_failed', curl_error( $handle ) );
```
I wonder what would have happened if I uninstalled curl. Can WordPress use other mechanisms to make http requests or is curl required?
|
For the record, I have uninstalled curl and wordpress was working on seamlessly.
So I confirm that curl is not a dependency of wordpress.
However, some plugins may require curl.
|
193,196 |
<p>In my white theme, there is no alt attribute configured for the home slider post. I added the alt text for the image through the media library interface. I added the following code to display the alt text/attribute. But it does not display:</p>
<pre><code><img class="homepage-slider_image" src="http://www.blabla.com/wp-content/uploads/2013/06/cms-website4-1800x800.jpg" alt="" />
</code></pre>
<p>Here is the code:</p>
<pre><code><?php
$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX.'homepage_slide_image', true);
if (!empty($image)) {
$image = json_decode($image);
$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);
if ( empty( $image_alt )) {
$image_alt = $attachment->post_title;
}
if ( empty( $image_alt )) {
$image_alt = $attachment->post_excerpt;
}
$image_title = $attachment->post_title;
$image_id = $image->id;
$image = wp_get_attachment_image_src( $image_id, 'blog-huge', false);
echo '<img class="homepage-slider_image" src="'.$image[0].'" alt="'. $image_alt .'" />';
}
?>
</code></pre>
|
[
{
"answer_id": 193198,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 5,
"selected": false,
"text": "<p>Your problem is that you are not providing the correct attachment's ID to <code>get_post_meta()</code> and <code>get_the_title()</code> functions.</p>\n\n<p>This is your code to get the <code>alt</code> of the image:</p>\n\n<pre><code>$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>And it is correct, but <code>$attachment->ID</code> is not defined in your code, so, the function does not return anything.</p>\n\n<p>Reading your code, it seems that you store the ID of the image as a meta field and then you get it with this code:</p>\n\n<pre><code>$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX.'homepage_slide_image', true);\n</code></pre>\n\n<p>So, assuming that <code>$image->id</code> is correct in your code, you should replace this:</p>\n\n<pre><code>$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>$image_alt = get_post_meta( $image->id, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>That is for getting the <code>alt</code>, to get the title:</p>\n\n<pre><code> $image_title = get_the_title( $image->id );\n</code></pre>\n"
},
{
"answer_id": 251043,
"author": "Benn",
"author_id": 67176,
"author_profile": "https://wordpress.stackexchange.com/users/67176",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX . 'homepage_slide_image', true);\nif (!empty($image)) {\n $image = json_decode($image);\n $image_id = $image->id;\n $img_meta = wp_prepare_attachment_for_js($image_id);\n $image_title = $img_meta['title'] == '' ? esc_html_e('Missing title','{domain}') : $img_meta['title'];\n $image_alt = $img_meta['alt'] == '' ? $image_title : $img_meta['alt'];\n $image_src = wp_get_attachment_image_src($image_id, 'blog-huge', false);\n\n echo '<img class=\"homepage-slider_image\" src=\"' . $image_src[0] . '\" alt=\"' . $image_alt . '\" />';\n\n}\n</code></pre>\n\n<p>please note that I did not test your <code>$image->id</code> , just assumed that you have the right attachment ID. The rest comes from <code>$img_meta</code>. If alt is missing we are using image title, if title is missing you will see \"Missing title\" text to nudge you to fill it in. </p>\n"
},
{
"answer_id": 265304,
"author": "DevTurtle",
"author_id": 104438,
"author_profile": "https://wordpress.stackexchange.com/users/104438",
"pm_score": 2,
"selected": false,
"text": "<p>Ok I found the answer that no one has on the net I been looking for days now. Keep in mine this only works if your theme or plugin is using the WP_Customize_Image_Control() if you are using WP_Customize_Media_Control() the get_theme_mod() will return the ID and not the url.</p>\n\n<p>For my solution I was using the newer version WP_Customize_Image_Control()</p>\n\n<p>A lot of posts on the forums have the get_attachment_id() which does not work anymore. I used attachment_url_to_postid()</p>\n\n<p>Here is how I was able to do it. Hope this helps someone out there</p>\n\n<pre><code>// This is getting the image / url\n$feature1 = get_theme_mod('feature_image_1');\n\n// This is getting the post id\n$feature1_id = attachment_url_to_postid($feature1);\n\n// This is getting the alt text from the image that is set in the media area\n$image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true );\n</code></pre>\n\n<p>Markup</p>\n\n<pre><code><a href=\"<?php echo $feature1_url; ?>\"><img class=\"img-responsive center-block\" src=\"<?php echo $feature1; ?>\" alt=\"<?php echo $image1_alt; ?>\"></a>\n</code></pre>\n"
},
{
"answer_id": 327064,
"author": "Dario Zadro",
"author_id": 17126,
"author_profile": "https://wordpress.stackexchange.com/users/17126",
"pm_score": 3,
"selected": false,
"text": "<p>I use a quick function in all my themes to get image attachment data:</p>\n\n<pre><code>//get attachment meta\nif ( !function_exists('wp_get_attachment') ) {\n function wp_get_attachment( $attachment_id )\n {\n $attachment = get_post( $attachment_id );\n return array(\n 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),\n 'caption' => $attachment->post_excerpt,\n 'description' => $attachment->post_content,\n 'href' => get_permalink( $attachment->ID ),\n 'src' => $attachment->guid,\n 'title' => $attachment->post_title\n );\n }\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 330599,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 7,
"selected": true,
"text": "<p>Came here as this post is among the top hits on the search engine when looking for WordPress image alt and title. Being rather surprised that none of the answers seem to provide a simple solution matching the question's title I'll drop what I came up with in the end hoping it helps future readers.</p>\n\n<pre><code>// An attachment/image ID is all that's needed to retrieve its alt and title attributes.\n$image_id = get_post_thumbnail_id();\n\n$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);\n\n$image_title = get_the_title($image_id);\n</code></pre>\n\n<p>As a bonus here's how to retrieve an image src. With the above attributes that's all we need to build a static image's markup.</p>\n\n<pre><code>$size = 'my-size' // Defaults to 'thumbnail' if omitted.\n\n$image_src = wp_get_attachment_image_src($image_id, $size)[0];\n</code></pre>\n"
},
{
"answer_id": 386321,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 1,
"selected": false,
"text": "<p>The true <strong>WordPress</strong> way would be to use provided function <code>get_image_tag()</code> to obtain image tag, providing id and alt arguments to the function. Other answers already explain how to get alt attribute.</p>\n<p>It also takes care of srcset and sizes attributes, which you should otherwise provide manually using <code>wp_get_attachment_image_srcset</code>, in order to have modern browser - optimized image loading.</p>\n"
}
] |
2015/07/01
|
[
"https://wordpress.stackexchange.com/questions/193196",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17703/"
] |
In my white theme, there is no alt attribute configured for the home slider post. I added the alt text for the image through the media library interface. I added the following code to display the alt text/attribute. But it does not display:
```
<img class="homepage-slider_image" src="http://www.blabla.com/wp-content/uploads/2013/06/cms-website4-1800x800.jpg" alt="" />
```
Here is the code:
```
<?php
$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX.'homepage_slide_image', true);
if (!empty($image)) {
$image = json_decode($image);
$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);
if ( empty( $image_alt )) {
$image_alt = $attachment->post_title;
}
if ( empty( $image_alt )) {
$image_alt = $attachment->post_excerpt;
}
$image_title = $attachment->post_title;
$image_id = $image->id;
$image = wp_get_attachment_image_src( $image_id, 'blog-huge', false);
echo '<img class="homepage-slider_image" src="'.$image[0].'" alt="'. $image_alt .'" />';
}
?>
```
|
Came here as this post is among the top hits on the search engine when looking for WordPress image alt and title. Being rather surprised that none of the answers seem to provide a simple solution matching the question's title I'll drop what I came up with in the end hoping it helps future readers.
```
// An attachment/image ID is all that's needed to retrieve its alt and title attributes.
$image_id = get_post_thumbnail_id();
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($image_id);
```
As a bonus here's how to retrieve an image src. With the above attributes that's all we need to build a static image's markup.
```
$size = 'my-size' // Defaults to 'thumbnail' if omitted.
$image_src = wp_get_attachment_image_src($image_id, $size)[0];
```
|
193,205 |
<p>I know this might be considered off topic but I am not sure where else to post this as it also pertains to WordPress as well as the plugin Contact Form 7. If you know where I should post this other than here please tell me.</p>
<hr>
<p>I am looking to have a conditionally required field. I have found code to work with but I think I am confusing myself and need some outside perspective.</p>
<p>What I need to work is if my check box is checked to "yes" it will make the drop down next to it required and if the check box is checked to "no" it is not required.</p>
<p>This is what I have as my form with the shortcode on the backend:</p>
<pre><code>If you have ordered from us in the past, do you already work with one of our outside sales representatives?
[checkbox* check-sales id:checksales "Yes" "No"]
If you checked "Yes" which representative do you generally deal with?
[select sales-rep id:sales include_blank "Marla" "Lisa" "Wendy" "Stacy" "Nicole" "Linda" "Jody" "Gisele" "Ray" "Craig"]
[submit]
</code></pre>
<p>And here is the php code example that goes into the functions.php file. </p>
<pre><code>function is_gmail($email) {
if(substr($email, -10) == '@gmail.com') {
return true;
} else {
return false;
};
};
function custom_email_validation_filter($result, $tag) {
$type = $tag['type'];
$name = $tag['name'];
if($name == 'your-email') { // Only apply to fields with the form field name of "your-email"
$the_value = $_POST[$name];
if(!is_gmail($the_value)){
$result['valid'] = false;
$result['reason'][$name] = 'This is not a gmail address!'; // Error message
};
};
return $result;
};
add_filter('wpcf7_validate_email','custom_email_validation_filter', 10, 2); // Email field
add_filter('wpcf7_validate_email*', 'custom_email_validation_filter', 10, 2); // Required Email field
</code></pre>
<p>I know this is geared towards email checking. However what I am confusing myself on is what I need to change in order to make this work for a checkbox and a dropdown.</p>
|
[
{
"answer_id": 193198,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 5,
"selected": false,
"text": "<p>Your problem is that you are not providing the correct attachment's ID to <code>get_post_meta()</code> and <code>get_the_title()</code> functions.</p>\n\n<p>This is your code to get the <code>alt</code> of the image:</p>\n\n<pre><code>$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>And it is correct, but <code>$attachment->ID</code> is not defined in your code, so, the function does not return anything.</p>\n\n<p>Reading your code, it seems that you store the ID of the image as a meta field and then you get it with this code:</p>\n\n<pre><code>$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX.'homepage_slide_image', true);\n</code></pre>\n\n<p>So, assuming that <code>$image->id</code> is correct in your code, you should replace this:</p>\n\n<pre><code>$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>$image_alt = get_post_meta( $image->id, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>That is for getting the <code>alt</code>, to get the title:</p>\n\n<pre><code> $image_title = get_the_title( $image->id );\n</code></pre>\n"
},
{
"answer_id": 251043,
"author": "Benn",
"author_id": 67176,
"author_profile": "https://wordpress.stackexchange.com/users/67176",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX . 'homepage_slide_image', true);\nif (!empty($image)) {\n $image = json_decode($image);\n $image_id = $image->id;\n $img_meta = wp_prepare_attachment_for_js($image_id);\n $image_title = $img_meta['title'] == '' ? esc_html_e('Missing title','{domain}') : $img_meta['title'];\n $image_alt = $img_meta['alt'] == '' ? $image_title : $img_meta['alt'];\n $image_src = wp_get_attachment_image_src($image_id, 'blog-huge', false);\n\n echo '<img class=\"homepage-slider_image\" src=\"' . $image_src[0] . '\" alt=\"' . $image_alt . '\" />';\n\n}\n</code></pre>\n\n<p>please note that I did not test your <code>$image->id</code> , just assumed that you have the right attachment ID. The rest comes from <code>$img_meta</code>. If alt is missing we are using image title, if title is missing you will see \"Missing title\" text to nudge you to fill it in. </p>\n"
},
{
"answer_id": 265304,
"author": "DevTurtle",
"author_id": 104438,
"author_profile": "https://wordpress.stackexchange.com/users/104438",
"pm_score": 2,
"selected": false,
"text": "<p>Ok I found the answer that no one has on the net I been looking for days now. Keep in mine this only works if your theme or plugin is using the WP_Customize_Image_Control() if you are using WP_Customize_Media_Control() the get_theme_mod() will return the ID and not the url.</p>\n\n<p>For my solution I was using the newer version WP_Customize_Image_Control()</p>\n\n<p>A lot of posts on the forums have the get_attachment_id() which does not work anymore. I used attachment_url_to_postid()</p>\n\n<p>Here is how I was able to do it. Hope this helps someone out there</p>\n\n<pre><code>// This is getting the image / url\n$feature1 = get_theme_mod('feature_image_1');\n\n// This is getting the post id\n$feature1_id = attachment_url_to_postid($feature1);\n\n// This is getting the alt text from the image that is set in the media area\n$image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true );\n</code></pre>\n\n<p>Markup</p>\n\n<pre><code><a href=\"<?php echo $feature1_url; ?>\"><img class=\"img-responsive center-block\" src=\"<?php echo $feature1; ?>\" alt=\"<?php echo $image1_alt; ?>\"></a>\n</code></pre>\n"
},
{
"answer_id": 327064,
"author": "Dario Zadro",
"author_id": 17126,
"author_profile": "https://wordpress.stackexchange.com/users/17126",
"pm_score": 3,
"selected": false,
"text": "<p>I use a quick function in all my themes to get image attachment data:</p>\n\n<pre><code>//get attachment meta\nif ( !function_exists('wp_get_attachment') ) {\n function wp_get_attachment( $attachment_id )\n {\n $attachment = get_post( $attachment_id );\n return array(\n 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),\n 'caption' => $attachment->post_excerpt,\n 'description' => $attachment->post_content,\n 'href' => get_permalink( $attachment->ID ),\n 'src' => $attachment->guid,\n 'title' => $attachment->post_title\n );\n }\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 330599,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 7,
"selected": true,
"text": "<p>Came here as this post is among the top hits on the search engine when looking for WordPress image alt and title. Being rather surprised that none of the answers seem to provide a simple solution matching the question's title I'll drop what I came up with in the end hoping it helps future readers.</p>\n\n<pre><code>// An attachment/image ID is all that's needed to retrieve its alt and title attributes.\n$image_id = get_post_thumbnail_id();\n\n$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);\n\n$image_title = get_the_title($image_id);\n</code></pre>\n\n<p>As a bonus here's how to retrieve an image src. With the above attributes that's all we need to build a static image's markup.</p>\n\n<pre><code>$size = 'my-size' // Defaults to 'thumbnail' if omitted.\n\n$image_src = wp_get_attachment_image_src($image_id, $size)[0];\n</code></pre>\n"
},
{
"answer_id": 386321,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 1,
"selected": false,
"text": "<p>The true <strong>WordPress</strong> way would be to use provided function <code>get_image_tag()</code> to obtain image tag, providing id and alt arguments to the function. Other answers already explain how to get alt attribute.</p>\n<p>It also takes care of srcset and sizes attributes, which you should otherwise provide manually using <code>wp_get_attachment_image_srcset</code>, in order to have modern browser - optimized image loading.</p>\n"
}
] |
2015/07/01
|
[
"https://wordpress.stackexchange.com/questions/193205",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8337/"
] |
I know this might be considered off topic but I am not sure where else to post this as it also pertains to WordPress as well as the plugin Contact Form 7. If you know where I should post this other than here please tell me.
---
I am looking to have a conditionally required field. I have found code to work with but I think I am confusing myself and need some outside perspective.
What I need to work is if my check box is checked to "yes" it will make the drop down next to it required and if the check box is checked to "no" it is not required.
This is what I have as my form with the shortcode on the backend:
```
If you have ordered from us in the past, do you already work with one of our outside sales representatives?
[checkbox* check-sales id:checksales "Yes" "No"]
If you checked "Yes" which representative do you generally deal with?
[select sales-rep id:sales include_blank "Marla" "Lisa" "Wendy" "Stacy" "Nicole" "Linda" "Jody" "Gisele" "Ray" "Craig"]
[submit]
```
And here is the php code example that goes into the functions.php file.
```
function is_gmail($email) {
if(substr($email, -10) == '@gmail.com') {
return true;
} else {
return false;
};
};
function custom_email_validation_filter($result, $tag) {
$type = $tag['type'];
$name = $tag['name'];
if($name == 'your-email') { // Only apply to fields with the form field name of "your-email"
$the_value = $_POST[$name];
if(!is_gmail($the_value)){
$result['valid'] = false;
$result['reason'][$name] = 'This is not a gmail address!'; // Error message
};
};
return $result;
};
add_filter('wpcf7_validate_email','custom_email_validation_filter', 10, 2); // Email field
add_filter('wpcf7_validate_email*', 'custom_email_validation_filter', 10, 2); // Required Email field
```
I know this is geared towards email checking. However what I am confusing myself on is what I need to change in order to make this work for a checkbox and a dropdown.
|
Came here as this post is among the top hits on the search engine when looking for WordPress image alt and title. Being rather surprised that none of the answers seem to provide a simple solution matching the question's title I'll drop what I came up with in the end hoping it helps future readers.
```
// An attachment/image ID is all that's needed to retrieve its alt and title attributes.
$image_id = get_post_thumbnail_id();
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($image_id);
```
As a bonus here's how to retrieve an image src. With the above attributes that's all we need to build a static image's markup.
```
$size = 'my-size' // Defaults to 'thumbnail' if omitted.
$image_src = wp_get_attachment_image_src($image_id, $size)[0];
```
|
193,212 |
<p>I have a template file that is being called via wp_ajax that returns data from a specific WooCommerce product.</p>
<p>In the "tabs" section of the template file every tab is working fine:</p>
<ul>
<li>Description - Good</li>
<li>Additional Information - Good</li>
<li>Custom Tab - Good</li>
</ul>
<p>The only tab not rendering tab panel content is the reviews tab.</p>
<p>Interestingly the Tab Link (<code>li</code>) shows up with the correct tab count. However, when you click the link and the review panel is no longer display:none and set as active - no content is shown. (This has been verified in dev tools).</p>
<p>The code that is calling all of the individual tabs is:</p>
<pre><code><?php call_user_func( $tab['callback'], $key, $tab ) ?>
</code></pre>
<p>Where <code>$tab</code> is an array with:</p>
<ul>
<li>title</li>
<li>priority</li>
<li>callback</li>
</ul>
<p>The reviews tab calls the WooCommerce specified <code>comments_template</code> callback.</p>
<p>This is <em>supposed</em> to trigger the hook in <code>class WC_Template_Loader</code>:</p>
<pre><code>add_filter( 'comments_template', array( __CLASS__, 'comments_template_loader' ) );
</code></pre>
<p>In testing I've var_dumped the <code>WC_Template_Loader</code> init function, and the init function, where the add_filters are located, is running.</p>
<p>However, when I var_dump a test string in the <code>comments_template_loader()</code> function, nothing is returned.</p>
<p>As an aside - all other WooCommerce generated content is rendered correctly (<code>global $woocommerce, $post, $product</code> are declared).</p>
<p>Why is this filter not running when seemingly all other default Wordpress tab filters are?</p>
|
[
{
"answer_id": 193198,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 5,
"selected": false,
"text": "<p>Your problem is that you are not providing the correct attachment's ID to <code>get_post_meta()</code> and <code>get_the_title()</code> functions.</p>\n\n<p>This is your code to get the <code>alt</code> of the image:</p>\n\n<pre><code>$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>And it is correct, but <code>$attachment->ID</code> is not defined in your code, so, the function does not return anything.</p>\n\n<p>Reading your code, it seems that you store the ID of the image as a meta field and then you get it with this code:</p>\n\n<pre><code>$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX.'homepage_slide_image', true);\n</code></pre>\n\n<p>So, assuming that <code>$image->id</code> is correct in your code, you should replace this:</p>\n\n<pre><code>$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>$image_alt = get_post_meta( $image->id, '_wp_attachment_image_alt', true);\n</code></pre>\n\n<p>That is for getting the <code>alt</code>, to get the title:</p>\n\n<pre><code> $image_title = get_the_title( $image->id );\n</code></pre>\n"
},
{
"answer_id": 251043,
"author": "Benn",
"author_id": 67176,
"author_profile": "https://wordpress.stackexchange.com/users/67176",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$image = get_post_meta(get_the_ID(), WPGRADE_PREFIX . 'homepage_slide_image', true);\nif (!empty($image)) {\n $image = json_decode($image);\n $image_id = $image->id;\n $img_meta = wp_prepare_attachment_for_js($image_id);\n $image_title = $img_meta['title'] == '' ? esc_html_e('Missing title','{domain}') : $img_meta['title'];\n $image_alt = $img_meta['alt'] == '' ? $image_title : $img_meta['alt'];\n $image_src = wp_get_attachment_image_src($image_id, 'blog-huge', false);\n\n echo '<img class=\"homepage-slider_image\" src=\"' . $image_src[0] . '\" alt=\"' . $image_alt . '\" />';\n\n}\n</code></pre>\n\n<p>please note that I did not test your <code>$image->id</code> , just assumed that you have the right attachment ID. The rest comes from <code>$img_meta</code>. If alt is missing we are using image title, if title is missing you will see \"Missing title\" text to nudge you to fill it in. </p>\n"
},
{
"answer_id": 265304,
"author": "DevTurtle",
"author_id": 104438,
"author_profile": "https://wordpress.stackexchange.com/users/104438",
"pm_score": 2,
"selected": false,
"text": "<p>Ok I found the answer that no one has on the net I been looking for days now. Keep in mine this only works if your theme or plugin is using the WP_Customize_Image_Control() if you are using WP_Customize_Media_Control() the get_theme_mod() will return the ID and not the url.</p>\n\n<p>For my solution I was using the newer version WP_Customize_Image_Control()</p>\n\n<p>A lot of posts on the forums have the get_attachment_id() which does not work anymore. I used attachment_url_to_postid()</p>\n\n<p>Here is how I was able to do it. Hope this helps someone out there</p>\n\n<pre><code>// This is getting the image / url\n$feature1 = get_theme_mod('feature_image_1');\n\n// This is getting the post id\n$feature1_id = attachment_url_to_postid($feature1);\n\n// This is getting the alt text from the image that is set in the media area\n$image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true );\n</code></pre>\n\n<p>Markup</p>\n\n<pre><code><a href=\"<?php echo $feature1_url; ?>\"><img class=\"img-responsive center-block\" src=\"<?php echo $feature1; ?>\" alt=\"<?php echo $image1_alt; ?>\"></a>\n</code></pre>\n"
},
{
"answer_id": 327064,
"author": "Dario Zadro",
"author_id": 17126,
"author_profile": "https://wordpress.stackexchange.com/users/17126",
"pm_score": 3,
"selected": false,
"text": "<p>I use a quick function in all my themes to get image attachment data:</p>\n\n<pre><code>//get attachment meta\nif ( !function_exists('wp_get_attachment') ) {\n function wp_get_attachment( $attachment_id )\n {\n $attachment = get_post( $attachment_id );\n return array(\n 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),\n 'caption' => $attachment->post_excerpt,\n 'description' => $attachment->post_content,\n 'href' => get_permalink( $attachment->ID ),\n 'src' => $attachment->guid,\n 'title' => $attachment->post_title\n );\n }\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 330599,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 7,
"selected": true,
"text": "<p>Came here as this post is among the top hits on the search engine when looking for WordPress image alt and title. Being rather surprised that none of the answers seem to provide a simple solution matching the question's title I'll drop what I came up with in the end hoping it helps future readers.</p>\n\n<pre><code>// An attachment/image ID is all that's needed to retrieve its alt and title attributes.\n$image_id = get_post_thumbnail_id();\n\n$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);\n\n$image_title = get_the_title($image_id);\n</code></pre>\n\n<p>As a bonus here's how to retrieve an image src. With the above attributes that's all we need to build a static image's markup.</p>\n\n<pre><code>$size = 'my-size' // Defaults to 'thumbnail' if omitted.\n\n$image_src = wp_get_attachment_image_src($image_id, $size)[0];\n</code></pre>\n"
},
{
"answer_id": 386321,
"author": "Lovor",
"author_id": 135704,
"author_profile": "https://wordpress.stackexchange.com/users/135704",
"pm_score": 1,
"selected": false,
"text": "<p>The true <strong>WordPress</strong> way would be to use provided function <code>get_image_tag()</code> to obtain image tag, providing id and alt arguments to the function. Other answers already explain how to get alt attribute.</p>\n<p>It also takes care of srcset and sizes attributes, which you should otherwise provide manually using <code>wp_get_attachment_image_srcset</code>, in order to have modern browser - optimized image loading.</p>\n"
}
] |
2015/07/01
|
[
"https://wordpress.stackexchange.com/questions/193212",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68087/"
] |
I have a template file that is being called via wp\_ajax that returns data from a specific WooCommerce product.
In the "tabs" section of the template file every tab is working fine:
* Description - Good
* Additional Information - Good
* Custom Tab - Good
The only tab not rendering tab panel content is the reviews tab.
Interestingly the Tab Link (`li`) shows up with the correct tab count. However, when you click the link and the review panel is no longer display:none and set as active - no content is shown. (This has been verified in dev tools).
The code that is calling all of the individual tabs is:
```
<?php call_user_func( $tab['callback'], $key, $tab ) ?>
```
Where `$tab` is an array with:
* title
* priority
* callback
The reviews tab calls the WooCommerce specified `comments_template` callback.
This is *supposed* to trigger the hook in `class WC_Template_Loader`:
```
add_filter( 'comments_template', array( __CLASS__, 'comments_template_loader' ) );
```
In testing I've var\_dumped the `WC_Template_Loader` init function, and the init function, where the add\_filters are located, is running.
However, when I var\_dump a test string in the `comments_template_loader()` function, nothing is returned.
As an aside - all other WooCommerce generated content is rendered correctly (`global $woocommerce, $post, $product` are declared).
Why is this filter not running when seemingly all other default Wordpress tab filters are?
|
Came here as this post is among the top hits on the search engine when looking for WordPress image alt and title. Being rather surprised that none of the answers seem to provide a simple solution matching the question's title I'll drop what I came up with in the end hoping it helps future readers.
```
// An attachment/image ID is all that's needed to retrieve its alt and title attributes.
$image_id = get_post_thumbnail_id();
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($image_id);
```
As a bonus here's how to retrieve an image src. With the above attributes that's all we need to build a static image's markup.
```
$size = 'my-size' // Defaults to 'thumbnail' if omitted.
$image_src = wp_get_attachment_image_src($image_id, $size)[0];
```
|
193,220 |
<p>Brand new to WordPress. Using it from GoDaddy and when I try to upload my video .mov file (it's only 10MB) I get an error saying it's not a valid media type. Any ideas? Thanks.</p>
|
[
{
"answer_id": 193264,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 0,
"selected": false,
"text": "<p>Check this another stack <a href=\"https://wordpress.stackexchange.com/questions/165706/embed-mov-file-via-add-media-not-working\">thread</a> it having same discussion and solution.</p>\n\n<p>Thanks</p>\n\n<p>Vee</p>\n"
},
{
"answer_id": 312185,
"author": "Santiago Cerro López",
"author_id": 149006,
"author_profile": "https://wordpress.stackexchange.com/users/149006",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>upload_mimes</code> filter and add mime for .mov files (<code>video/quicktime</code>).</p>\n\n<pre><code>add_filter( 'upload_mimes', 'customizeMimeTypes', 10, 1 );\nfunction customizeMimeTypes( $mimeTypes) {\n $mimeTypes['mov'] = 'video/quicktime';\n return $mimeTypes;\n}\n</code></pre>\n\n<p>If you want to embed video with media library you can use <code>wp_video_extensions</code> filter.</p>\n\n<pre><code>add_filter( 'wp_video_extensions', 'addMovToWPVideo');\nfunction addMovToWPVideo( $extensions ) {\n $extensions [] = 'mov';\n return $extensions ;\n}\n</code></pre>\n\n<p>More info:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_video_extensions/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_video_extensions/</a>\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes</a></p>\n\n<p>Hope this helps you!</p>\n\n<p>Note: check php max upload file size in php.ini too!</p>\n"
}
] |
2015/07/01
|
[
"https://wordpress.stackexchange.com/questions/193220",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75520/"
] |
Brand new to WordPress. Using it from GoDaddy and when I try to upload my video .mov file (it's only 10MB) I get an error saying it's not a valid media type. Any ideas? Thanks.
|
You can use `upload_mimes` filter and add mime for .mov files (`video/quicktime`).
```
add_filter( 'upload_mimes', 'customizeMimeTypes', 10, 1 );
function customizeMimeTypes( $mimeTypes) {
$mimeTypes['mov'] = 'video/quicktime';
return $mimeTypes;
}
```
If you want to embed video with media library you can use `wp_video_extensions` filter.
```
add_filter( 'wp_video_extensions', 'addMovToWPVideo');
function addMovToWPVideo( $extensions ) {
$extensions [] = 'mov';
return $extensions ;
}
```
More info:
<https://developer.wordpress.org/reference/hooks/wp_video_extensions/>
<https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes>
Hope this helps you!
Note: check php max upload file size in php.ini too!
|
193,222 |
<p>Im trying to create a topics "section" similar to what Justin Tadlock has on <a href="http://justintadlock.com/topics" rel="nofollow">his site</a> but i'm not sure <strong>how</strong> he is doing this. Categories? Tags? or what?</p>
<p>I tried changing the Category base to topics as the instructions state: </p>
<blockquote>
<p>If you like, you may enter custom structures for your category and tag URLs here. For example, using topics as your category base would make your category links like <a href="http://local.dev/topics/uncategorized/" rel="nofollow">http://local.dev/topics/uncategorized/</a>.</p>
</blockquote>
<p>Now assuming my category is "foo", when I visit <code>http://local.dev/topics/foo/</code> I see the proper listing of articles categorized as "foo".</p>
<p>But when I back out to <code>http://local.dev/topics/</code> i get ...nothing. Whereas I assumed I would get a list of all categories.</p>
<p>Again looking at Justin Tadlock's site, it appears each item in his <a href="http://justintadlock.com/topics" rel="nofollow">"Topics Archive"</a> is actually a tag?</p>
<p>How is this done?</p>
<p>Is he using a Custom taxonomy or what?
How do I approach this?</p>
<p>Please advise.</p>
<p>--pkd</p>
|
[
{
"answer_id": 193264,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 0,
"selected": false,
"text": "<p>Check this another stack <a href=\"https://wordpress.stackexchange.com/questions/165706/embed-mov-file-via-add-media-not-working\">thread</a> it having same discussion and solution.</p>\n\n<p>Thanks</p>\n\n<p>Vee</p>\n"
},
{
"answer_id": 312185,
"author": "Santiago Cerro López",
"author_id": 149006,
"author_profile": "https://wordpress.stackexchange.com/users/149006",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>upload_mimes</code> filter and add mime for .mov files (<code>video/quicktime</code>).</p>\n\n<pre><code>add_filter( 'upload_mimes', 'customizeMimeTypes', 10, 1 );\nfunction customizeMimeTypes( $mimeTypes) {\n $mimeTypes['mov'] = 'video/quicktime';\n return $mimeTypes;\n}\n</code></pre>\n\n<p>If you want to embed video with media library you can use <code>wp_video_extensions</code> filter.</p>\n\n<pre><code>add_filter( 'wp_video_extensions', 'addMovToWPVideo');\nfunction addMovToWPVideo( $extensions ) {\n $extensions [] = 'mov';\n return $extensions ;\n}\n</code></pre>\n\n<p>More info:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_video_extensions/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_video_extensions/</a>\n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes</a></p>\n\n<p>Hope this helps you!</p>\n\n<p>Note: check php max upload file size in php.ini too!</p>\n"
}
] |
2015/07/01
|
[
"https://wordpress.stackexchange.com/questions/193222",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12116/"
] |
Im trying to create a topics "section" similar to what Justin Tadlock has on [his site](http://justintadlock.com/topics) but i'm not sure **how** he is doing this. Categories? Tags? or what?
I tried changing the Category base to topics as the instructions state:
>
> If you like, you may enter custom structures for your category and tag URLs here. For example, using topics as your category base would make your category links like <http://local.dev/topics/uncategorized/>.
>
>
>
Now assuming my category is "foo", when I visit `http://local.dev/topics/foo/` I see the proper listing of articles categorized as "foo".
But when I back out to `http://local.dev/topics/` i get ...nothing. Whereas I assumed I would get a list of all categories.
Again looking at Justin Tadlock's site, it appears each item in his ["Topics Archive"](http://justintadlock.com/topics) is actually a tag?
How is this done?
Is he using a Custom taxonomy or what?
How do I approach this?
Please advise.
--pkd
|
You can use `upload_mimes` filter and add mime for .mov files (`video/quicktime`).
```
add_filter( 'upload_mimes', 'customizeMimeTypes', 10, 1 );
function customizeMimeTypes( $mimeTypes) {
$mimeTypes['mov'] = 'video/quicktime';
return $mimeTypes;
}
```
If you want to embed video with media library you can use `wp_video_extensions` filter.
```
add_filter( 'wp_video_extensions', 'addMovToWPVideo');
function addMovToWPVideo( $extensions ) {
$extensions [] = 'mov';
return $extensions ;
}
```
More info:
<https://developer.wordpress.org/reference/hooks/wp_video_extensions/>
<https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes>
Hope this helps you!
Note: check php max upload file size in php.ini too!
|
193,284 |
<p>Is there a way to query all pages and order them by <code>menu_order</code> <strong>but</strong> ignore those pages that the default value of <code>0</code>?</p>
<p>I was trying to do something like this:</p>
<pre><code> $the_query = array(
'post_type' => self::POST_TYPE,
'posts_per_page' => $total,
'product_cat' => $product_category_name,
'orderby' => $orderby,
'suppress_filters' => '0'
);
</code></pre>
<p>Or do I need to create a filter to alter the <code>WP_Query</code>? any ideas? </p>
<p>cheers</p>
|
[
{
"answer_id": 193291,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can try the following <s>(untested)</s> mini plugin:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Support for ignoring the default menu order in WP_Query\n * Description: Uses the _ignore_default_menu_order argument\n * Plugin URI: http://wordpress.stackexchange.com/a/193291/26350\n */\nadd_filter( 'posts_where', function( $where, $q )\n{\n global $wpdb;\n\n if( (bool) $q->get( '_ignore_default_menu_order' ) ) {\n $where .= \"AND {$wpdb->posts}.menu_order <> 0\";\n }\n return $where;\n\n}, 10, 2 );\n</code></pre>\n\n<p>Then you should be able to use the new custom query argument like:</p>\n\n<pre><code>$query = new WP_Query( \n [ \n '_ignore_default_menu_order' => true,\n ]\n);\n</code></pre>\n\n<p>to ignore posts with the default menu order (<code>0</code>).</p>\n\n<p>You could also extend this to support any menu order as user input.</p>\n"
},
{
"answer_id": 331097,
"author": "Prakash Kumar",
"author_id": 162772,
"author_profile": "https://wordpress.stackexchange.com/users/162772",
"pm_score": 0,
"selected": false,
"text": "<p>The code below worked fine for me even with the custom ordering plugins also like \n<a href=\"https://wordpress.org/plugins/intuitive-custom-post-order/\" rel=\"nofollow noreferrer\">Intuitive CPO</a></p>\n\n<pre><code>add_action( 'pre_get_posts', 'custom_pre_get_posts', 20, 1);\n\nfunction custom_pre_get_posts($wp_query) {\n\n if(isset($wp_query->query['_ignore_default_menu_order']) && $wp_query->query['_ignore_default_menu_order']) {\n $wp_query->set( 'orderby', $wp_query->query['orderby'] );\n $wp_query->set( 'order', $wp_query->query['order'] );\n unset($wp_query->query_vars['_ignore_default_menu_order']);\n }\n}\n</code></pre>\n"
}
] |
2015/07/02
|
[
"https://wordpress.stackexchange.com/questions/193284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35073/"
] |
Is there a way to query all pages and order them by `menu_order` **but** ignore those pages that the default value of `0`?
I was trying to do something like this:
```
$the_query = array(
'post_type' => self::POST_TYPE,
'posts_per_page' => $total,
'product_cat' => $product_category_name,
'orderby' => $orderby,
'suppress_filters' => '0'
);
```
Or do I need to create a filter to alter the `WP_Query`? any ideas?
cheers
|
You can try the following ~~(untested)~~ mini plugin:
```
<?php
/**
* Plugin Name: Support for ignoring the default menu order in WP_Query
* Description: Uses the _ignore_default_menu_order argument
* Plugin URI: http://wordpress.stackexchange.com/a/193291/26350
*/
add_filter( 'posts_where', function( $where, $q )
{
global $wpdb;
if( (bool) $q->get( '_ignore_default_menu_order' ) ) {
$where .= "AND {$wpdb->posts}.menu_order <> 0";
}
return $where;
}, 10, 2 );
```
Then you should be able to use the new custom query argument like:
```
$query = new WP_Query(
[
'_ignore_default_menu_order' => true,
]
);
```
to ignore posts with the default menu order (`0`).
You could also extend this to support any menu order as user input.
|
193,286 |
<p>I just want to once and for all get some clarity on jQuery within Wordpress as I can never remember from one project to the next how things should be done.</p>
<p>The particular example I am talking about is for flexslider. On the site I am working on now I have tried:</p>
<pre><code>jQuery(document).ready(function($) {
$('.flexslider').flexslider({
slideshow: true,
animationSpeed: 400,
initDelay: 100,
animation: "slide",
animationLoop: true,
itemWidth: 258,
itemMargin: 26
});
});
</code></pre>
<p>This works in Opera but not Firefox, and have tried:</p>
<pre><code>jQuery(document).ready(function($) {
jQuery('.flexslider').flexslider({
slideshow: true,
animationSpeed: 400,
initDelay: 100,
animation: "slide",
animationLoop: true,
itemWidth: 258,
itemMargin: 26
});
});
</code></pre>
<p>This works in Firefox but not Opera, other browsers not yet tested.</p>
<p>What is the correct way to do this to work in all browsers?</p>
<p>Thanks</p>
|
[
{
"answer_id": 193294,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>To make jQuery work in noconflict mode you need to wrap all the functions in your js-file like this:</p>\n\n<pre><code>jQuery(window).ready(function( $ ) { Your functions here });\n</code></pre>\n\n<p>You can now use the $ selector as usual:</p>\n\n<pre><code>$(window).load(function(){ Stuff here });\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$(document).ready(function(){ Stuff here });\n</code></pre>\n\n<p>I usually use the former, because document.ready sometimes conflicts with the Wordpress theme modifier (no idea why).</p>\n"
},
{
"answer_id": 193295,
"author": "rzepak",
"author_id": 11897,
"author_profile": "https://wordpress.stackexchange.com/users/11897",
"pm_score": 2,
"selected": true,
"text": "<p>I prefer this:</p>\n\n<pre><code>(function($){\n \"use strict\";\n $(document).ready(function(){\n $('.flexslider').flexslider({\n slideshow: true,\n animationSpeed: 400,\n initDelay: 100,\n animation: \"slide\",\n animationLoop: true,\n itemWidth: 258,\n itemMargin: 26\n });\n });\n})(this.jQuery);\n</code></pre>\n"
},
{
"answer_id": 193326,
"author": "Adrian",
"author_id": 34820,
"author_profile": "https://wordpress.stackexchange.com/users/34820",
"pm_score": -1,
"selected": false,
"text": "<p>To answer this question, it is more about how you call jQuery rather than how you call the function. </p>\n\n<p>I have just changed my direct link to jQuery to the following:</p>\n\n<pre><code>if (!is_admin()) add_action(\"wp_enqueue_scripts\", \"my_jquery_enqueue\", 11);\nfunction my_jquery_enqueue() {\n wp_deregister_script('jquery');\n wp_register_script('jquery', \"http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\", false, null);\n wp_enqueue_script('jquery');\n}\n</code></pre>\n\n<p>This is taken frmo CSS Tricks and posted in functions.php, this now makes the following work on all browsers:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n $('.flexslider').flexslider({\n slideshow: true,\n animationSpeed: 400,\n initDelay: 100,\n animation: \"slide\",\n animationLoop: true,\n itemWidth: 258,\n itemMargin: 26\n });\n});\n</code></pre>\n"
}
] |
2015/07/02
|
[
"https://wordpress.stackexchange.com/questions/193286",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34820/"
] |
I just want to once and for all get some clarity on jQuery within Wordpress as I can never remember from one project to the next how things should be done.
The particular example I am talking about is for flexslider. On the site I am working on now I have tried:
```
jQuery(document).ready(function($) {
$('.flexslider').flexslider({
slideshow: true,
animationSpeed: 400,
initDelay: 100,
animation: "slide",
animationLoop: true,
itemWidth: 258,
itemMargin: 26
});
});
```
This works in Opera but not Firefox, and have tried:
```
jQuery(document).ready(function($) {
jQuery('.flexslider').flexslider({
slideshow: true,
animationSpeed: 400,
initDelay: 100,
animation: "slide",
animationLoop: true,
itemWidth: 258,
itemMargin: 26
});
});
```
This works in Firefox but not Opera, other browsers not yet tested.
What is the correct way to do this to work in all browsers?
Thanks
|
I prefer this:
```
(function($){
"use strict";
$(document).ready(function(){
$('.flexslider').flexslider({
slideshow: true,
animationSpeed: 400,
initDelay: 100,
animation: "slide",
animationLoop: true,
itemWidth: 258,
itemMargin: 26
});
});
})(this.jQuery);
```
|
193,325 |
<p>Sorry for the basic question, every Google query I try yields no useful results.</p>
<p>How do I change the search results directory in Wordpress? Currently all searches need to be on the <code>root</code> to produce results. i.e.</p>
<p><code>www.domain.tld/?s=query</code></p>
<p>But I'd like to be able to have two searches (which I currently already have working independently):</p>
<ul>
<li><code>www.domain.tld/blog/?s=query</code></li>
<li><code>www.domain.tld/somethingelse/?s=query</code></li>
</ul>
<p>I've tried adding the directories to my search form <code>action</code>s, and although I've got Wordpress loading the right template for each search, the searches never produce any results. They only produce results when searching on the <code>root</code>.</p>
<hr>
<p>So it turns out that coming back to this I was able to just include the directory in the search form action. The strange this is that I'd experimented with this at quite some length - and gotten nowhere. So I think that something else might have been at play preventing this from working for some reason. Annoying mystery!</p>
|
[
{
"answer_id": 193407,
"author": "Amirmasoud",
"author_id": 58133,
"author_profile": "https://wordpress.stackexchange.com/users/58133",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this with functions.php file:</p>\n\n<pre><code>function fb_change_search_url_rewrite() {\n if ( is_search() && ! empty( $_GET['s'] ) ) {\n wp_redirect( home_url( \"/search/\" ) . urlencode( get_query_var( 's' ) ) );\n exit();\n } \n}\nadd_action( 'template_redirect', 'fb_change_search_url_rewrite' );\n</code></pre>\n\n<p>also possible via htacces rules:</p>\n\n<pre><code># search redirect\n# this will take anything in the query string, minus any extraneous values, and turn them into a clean working url\nRewriteCond %{QUERY_STRING} \\\\?s=([^&]+) [NC]\nRewriteRule ^$ /search/%1/? [NC,R,L]\n</code></pre>\n\n<p><a href=\"http://wpengineer.com/2258/change-the-search-url-of-wordpress/\" rel=\"nofollow\">source</a></p>\n"
},
{
"answer_id": 229015,
"author": "Isu",
"author_id": 102934,
"author_profile": "https://wordpress.stackexchange.com/users/102934",
"pm_score": 3,
"selected": false,
"text": "<p>You can create a new page. Let's say you want to have:\n<code>http://example.com/mysearch/</code> </p>\n\n<p>Create a page that will have that URL structure.\nNext, Search form -> Go to and on you search form action do:</p>\n\n<pre><code><form role=\"filter-search\" method=\"get\" id=\"sd_searchform_filter\" action=\"<?php \n echo home_url( '/mysearch/' ); ?>\">...\n</code></pre>\n\n<p>Now go to <code>functions.php</code> (or where you want this function)\nand now we doing tricks!</p>\n\n<pre><code>function isu_search_url( $query ) {\n\n $page_id = 12; // This is ID of page with your structure -> http://example.com/mysearch/\n $per_page = 10;\n $post_type = 'activity'; // I just modify a bit this querry\n\n // Now we must edit only query on this one page\n if ( !is_admin() && $query->is_main_query() && $query->queried_object->ID == $page_id ) {\n // I like to have additional class if it is special Query like for activity as you can see\n add_filter( 'body_class', function( $classes ) {\n $classes[] = 'filter-search';\n return $classes;\n } );\n $query->set( 'pagename', '' ); // we reset this one to empty!\n $query->set( 'posts_per_page', $per_page ); // set post per page or dont ... :)\n $query->set( 'post_type', $post_type ); // we set post type if we need (I need in this case)\n // 3 important steps (make sure to do it, and you not on archive page, \n // or just fails if it is archive, use e.g. Query monitor plugin )\n $query->is_search = true; // We making WP think it is Search page \n $query->is_page = false; // disable unnecessary WP condition\n $query->is_singular = false; // disable unnecessary WP condition\n }\n}\nadd_action( 'pre_get_posts', 'isu_search_url' );\n</code></pre>\n\n<p>Now it works, you don't have to change <code>.htaccess</code>, etc.\nPagination will work properly. :)</p>\n"
}
] |
2015/07/02
|
[
"https://wordpress.stackexchange.com/questions/193325",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51906/"
] |
Sorry for the basic question, every Google query I try yields no useful results.
How do I change the search results directory in Wordpress? Currently all searches need to be on the `root` to produce results. i.e.
`www.domain.tld/?s=query`
But I'd like to be able to have two searches (which I currently already have working independently):
* `www.domain.tld/blog/?s=query`
* `www.domain.tld/somethingelse/?s=query`
I've tried adding the directories to my search form `action`s, and although I've got Wordpress loading the right template for each search, the searches never produce any results. They only produce results when searching on the `root`.
---
So it turns out that coming back to this I was able to just include the directory in the search form action. The strange this is that I'd experimented with this at quite some length - and gotten nowhere. So I think that something else might have been at play preventing this from working for some reason. Annoying mystery!
|
You can create a new page. Let's say you want to have:
`http://example.com/mysearch/`
Create a page that will have that URL structure.
Next, Search form -> Go to and on you search form action do:
```
<form role="filter-search" method="get" id="sd_searchform_filter" action="<?php
echo home_url( '/mysearch/' ); ?>">...
```
Now go to `functions.php` (or where you want this function)
and now we doing tricks!
```
function isu_search_url( $query ) {
$page_id = 12; // This is ID of page with your structure -> http://example.com/mysearch/
$per_page = 10;
$post_type = 'activity'; // I just modify a bit this querry
// Now we must edit only query on this one page
if ( !is_admin() && $query->is_main_query() && $query->queried_object->ID == $page_id ) {
// I like to have additional class if it is special Query like for activity as you can see
add_filter( 'body_class', function( $classes ) {
$classes[] = 'filter-search';
return $classes;
} );
$query->set( 'pagename', '' ); // we reset this one to empty!
$query->set( 'posts_per_page', $per_page ); // set post per page or dont ... :)
$query->set( 'post_type', $post_type ); // we set post type if we need (I need in this case)
// 3 important steps (make sure to do it, and you not on archive page,
// or just fails if it is archive, use e.g. Query monitor plugin )
$query->is_search = true; // We making WP think it is Search page
$query->is_page = false; // disable unnecessary WP condition
$query->is_singular = false; // disable unnecessary WP condition
}
}
add_action( 'pre_get_posts', 'isu_search_url' );
```
Now it works, you don't have to change `.htaccess`, etc.
Pagination will work properly. :)
|
193,334 |
<p>I couldn't find anything on Google or on here about best practice for data that is not really Wordpress related.</p>
<p>Say we have a database of clients that we'll be accessing through PHP/SQL. Should I just create new tables within the wordpress database or is it good practice to keep these in completely separate databases?</p>
<p>Currently its very basic and was actually being done as an external CSV. Moving forward though we want it to be a database and eventually clients will have a login area as well.</p>
|
[
{
"answer_id": 193407,
"author": "Amirmasoud",
"author_id": 58133,
"author_profile": "https://wordpress.stackexchange.com/users/58133",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this with functions.php file:</p>\n\n<pre><code>function fb_change_search_url_rewrite() {\n if ( is_search() && ! empty( $_GET['s'] ) ) {\n wp_redirect( home_url( \"/search/\" ) . urlencode( get_query_var( 's' ) ) );\n exit();\n } \n}\nadd_action( 'template_redirect', 'fb_change_search_url_rewrite' );\n</code></pre>\n\n<p>also possible via htacces rules:</p>\n\n<pre><code># search redirect\n# this will take anything in the query string, minus any extraneous values, and turn them into a clean working url\nRewriteCond %{QUERY_STRING} \\\\?s=([^&]+) [NC]\nRewriteRule ^$ /search/%1/? [NC,R,L]\n</code></pre>\n\n<p><a href=\"http://wpengineer.com/2258/change-the-search-url-of-wordpress/\" rel=\"nofollow\">source</a></p>\n"
},
{
"answer_id": 229015,
"author": "Isu",
"author_id": 102934,
"author_profile": "https://wordpress.stackexchange.com/users/102934",
"pm_score": 3,
"selected": false,
"text": "<p>You can create a new page. Let's say you want to have:\n<code>http://example.com/mysearch/</code> </p>\n\n<p>Create a page that will have that URL structure.\nNext, Search form -> Go to and on you search form action do:</p>\n\n<pre><code><form role=\"filter-search\" method=\"get\" id=\"sd_searchform_filter\" action=\"<?php \n echo home_url( '/mysearch/' ); ?>\">...\n</code></pre>\n\n<p>Now go to <code>functions.php</code> (or where you want this function)\nand now we doing tricks!</p>\n\n<pre><code>function isu_search_url( $query ) {\n\n $page_id = 12; // This is ID of page with your structure -> http://example.com/mysearch/\n $per_page = 10;\n $post_type = 'activity'; // I just modify a bit this querry\n\n // Now we must edit only query on this one page\n if ( !is_admin() && $query->is_main_query() && $query->queried_object->ID == $page_id ) {\n // I like to have additional class if it is special Query like for activity as you can see\n add_filter( 'body_class', function( $classes ) {\n $classes[] = 'filter-search';\n return $classes;\n } );\n $query->set( 'pagename', '' ); // we reset this one to empty!\n $query->set( 'posts_per_page', $per_page ); // set post per page or dont ... :)\n $query->set( 'post_type', $post_type ); // we set post type if we need (I need in this case)\n // 3 important steps (make sure to do it, and you not on archive page, \n // or just fails if it is archive, use e.g. Query monitor plugin )\n $query->is_search = true; // We making WP think it is Search page \n $query->is_page = false; // disable unnecessary WP condition\n $query->is_singular = false; // disable unnecessary WP condition\n }\n}\nadd_action( 'pre_get_posts', 'isu_search_url' );\n</code></pre>\n\n<p>Now it works, you don't have to change <code>.htaccess</code>, etc.\nPagination will work properly. :)</p>\n"
}
] |
2015/07/02
|
[
"https://wordpress.stackexchange.com/questions/193334",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17954/"
] |
I couldn't find anything on Google or on here about best practice for data that is not really Wordpress related.
Say we have a database of clients that we'll be accessing through PHP/SQL. Should I just create new tables within the wordpress database or is it good practice to keep these in completely separate databases?
Currently its very basic and was actually being done as an external CSV. Moving forward though we want it to be a database and eventually clients will have a login area as well.
|
You can create a new page. Let's say you want to have:
`http://example.com/mysearch/`
Create a page that will have that URL structure.
Next, Search form -> Go to and on you search form action do:
```
<form role="filter-search" method="get" id="sd_searchform_filter" action="<?php
echo home_url( '/mysearch/' ); ?>">...
```
Now go to `functions.php` (or where you want this function)
and now we doing tricks!
```
function isu_search_url( $query ) {
$page_id = 12; // This is ID of page with your structure -> http://example.com/mysearch/
$per_page = 10;
$post_type = 'activity'; // I just modify a bit this querry
// Now we must edit only query on this one page
if ( !is_admin() && $query->is_main_query() && $query->queried_object->ID == $page_id ) {
// I like to have additional class if it is special Query like for activity as you can see
add_filter( 'body_class', function( $classes ) {
$classes[] = 'filter-search';
return $classes;
} );
$query->set( 'pagename', '' ); // we reset this one to empty!
$query->set( 'posts_per_page', $per_page ); // set post per page or dont ... :)
$query->set( 'post_type', $post_type ); // we set post type if we need (I need in this case)
// 3 important steps (make sure to do it, and you not on archive page,
// or just fails if it is archive, use e.g. Query monitor plugin )
$query->is_search = true; // We making WP think it is Search page
$query->is_page = false; // disable unnecessary WP condition
$query->is_singular = false; // disable unnecessary WP condition
}
}
add_action( 'pre_get_posts', 'isu_search_url' );
```
Now it works, you don't have to change `.htaccess`, etc.
Pagination will work properly. :)
|
193,344 |
<p>I'm migrating my wordpress-blog and so imported my complete content with WordPress Importer 0.6.1. (which is the latest today (July, 2th 2015). My mySQL-server version is 5.1.56-community. </p>
<p>Unfortunatley two problems appear on my new blog after import:<br>
1.) all my backslashes are gone, e.g.</p>
<pre><code>C:\Program Files -> C:Program Files
</code></pre>
<p>2.) some signs inside code-areas (formatted with the "SyntaxHighlighter Evolved" plugin) are encrypted with HTML entities, e.g.</p>
<pre><code> < -> &lt;
> -> &gt;
" -> &quot;
(...)
</code></pre>
<p>3.) Links inside code-area (formatted with the "SyntaxHighlighter Evolved" plugin) are replaced, e.g.</p>
<pre><code>http://www.google.com -> <a class="linkification-ext" href="http://www.google.com" title="Linkification: http://www.google.com">http://www.google.com</a>
</code></pre>
<p>First I looked at the backup.xml (which was created by the export tool of wordpress.com) and all backslashes are shown correct there.<br>
Second I looked in the database and really all backslashes are missing.</p>
<p>Creating a plugin before export (<a href="https://wordpress.stackexchange.com/a/50560/75467">https://wordpress.stackexchange.com/a/50560/75467</a>) isn't a solution for me, because the hoster (wordpress.com) doesn't let me that deep in the system.</p>
|
[
{
"answer_id": 193407,
"author": "Amirmasoud",
"author_id": 58133,
"author_profile": "https://wordpress.stackexchange.com/users/58133",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this with functions.php file:</p>\n\n<pre><code>function fb_change_search_url_rewrite() {\n if ( is_search() && ! empty( $_GET['s'] ) ) {\n wp_redirect( home_url( \"/search/\" ) . urlencode( get_query_var( 's' ) ) );\n exit();\n } \n}\nadd_action( 'template_redirect', 'fb_change_search_url_rewrite' );\n</code></pre>\n\n<p>also possible via htacces rules:</p>\n\n<pre><code># search redirect\n# this will take anything in the query string, minus any extraneous values, and turn them into a clean working url\nRewriteCond %{QUERY_STRING} \\\\?s=([^&]+) [NC]\nRewriteRule ^$ /search/%1/? [NC,R,L]\n</code></pre>\n\n<p><a href=\"http://wpengineer.com/2258/change-the-search-url-of-wordpress/\" rel=\"nofollow\">source</a></p>\n"
},
{
"answer_id": 229015,
"author": "Isu",
"author_id": 102934,
"author_profile": "https://wordpress.stackexchange.com/users/102934",
"pm_score": 3,
"selected": false,
"text": "<p>You can create a new page. Let's say you want to have:\n<code>http://example.com/mysearch/</code> </p>\n\n<p>Create a page that will have that URL structure.\nNext, Search form -> Go to and on you search form action do:</p>\n\n<pre><code><form role=\"filter-search\" method=\"get\" id=\"sd_searchform_filter\" action=\"<?php \n echo home_url( '/mysearch/' ); ?>\">...\n</code></pre>\n\n<p>Now go to <code>functions.php</code> (or where you want this function)\nand now we doing tricks!</p>\n\n<pre><code>function isu_search_url( $query ) {\n\n $page_id = 12; // This is ID of page with your structure -> http://example.com/mysearch/\n $per_page = 10;\n $post_type = 'activity'; // I just modify a bit this querry\n\n // Now we must edit only query on this one page\n if ( !is_admin() && $query->is_main_query() && $query->queried_object->ID == $page_id ) {\n // I like to have additional class if it is special Query like for activity as you can see\n add_filter( 'body_class', function( $classes ) {\n $classes[] = 'filter-search';\n return $classes;\n } );\n $query->set( 'pagename', '' ); // we reset this one to empty!\n $query->set( 'posts_per_page', $per_page ); // set post per page or dont ... :)\n $query->set( 'post_type', $post_type ); // we set post type if we need (I need in this case)\n // 3 important steps (make sure to do it, and you not on archive page, \n // or just fails if it is archive, use e.g. Query monitor plugin )\n $query->is_search = true; // We making WP think it is Search page \n $query->is_page = false; // disable unnecessary WP condition\n $query->is_singular = false; // disable unnecessary WP condition\n }\n}\nadd_action( 'pre_get_posts', 'isu_search_url' );\n</code></pre>\n\n<p>Now it works, you don't have to change <code>.htaccess</code>, etc.\nPagination will work properly. :)</p>\n"
}
] |
2015/07/02
|
[
"https://wordpress.stackexchange.com/questions/193344",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75467/"
] |
I'm migrating my wordpress-blog and so imported my complete content with WordPress Importer 0.6.1. (which is the latest today (July, 2th 2015). My mySQL-server version is 5.1.56-community.
Unfortunatley two problems appear on my new blog after import:
1.) all my backslashes are gone, e.g.
```
C:\Program Files -> C:Program Files
```
2.) some signs inside code-areas (formatted with the "SyntaxHighlighter Evolved" plugin) are encrypted with HTML entities, e.g.
```
< -> <
> -> >
" -> "
(...)
```
3.) Links inside code-area (formatted with the "SyntaxHighlighter Evolved" plugin) are replaced, e.g.
```
http://www.google.com -> <a class="linkification-ext" href="http://www.google.com" title="Linkification: http://www.google.com">http://www.google.com</a>
```
First I looked at the backup.xml (which was created by the export tool of wordpress.com) and all backslashes are shown correct there.
Second I looked in the database and really all backslashes are missing.
Creating a plugin before export (<https://wordpress.stackexchange.com/a/50560/75467>) isn't a solution for me, because the hoster (wordpress.com) doesn't let me that deep in the system.
|
You can create a new page. Let's say you want to have:
`http://example.com/mysearch/`
Create a page that will have that URL structure.
Next, Search form -> Go to and on you search form action do:
```
<form role="filter-search" method="get" id="sd_searchform_filter" action="<?php
echo home_url( '/mysearch/' ); ?>">...
```
Now go to `functions.php` (or where you want this function)
and now we doing tricks!
```
function isu_search_url( $query ) {
$page_id = 12; // This is ID of page with your structure -> http://example.com/mysearch/
$per_page = 10;
$post_type = 'activity'; // I just modify a bit this querry
// Now we must edit only query on this one page
if ( !is_admin() && $query->is_main_query() && $query->queried_object->ID == $page_id ) {
// I like to have additional class if it is special Query like for activity as you can see
add_filter( 'body_class', function( $classes ) {
$classes[] = 'filter-search';
return $classes;
} );
$query->set( 'pagename', '' ); // we reset this one to empty!
$query->set( 'posts_per_page', $per_page ); // set post per page or dont ... :)
$query->set( 'post_type', $post_type ); // we set post type if we need (I need in this case)
// 3 important steps (make sure to do it, and you not on archive page,
// or just fails if it is archive, use e.g. Query monitor plugin )
$query->is_search = true; // We making WP think it is Search page
$query->is_page = false; // disable unnecessary WP condition
$query->is_singular = false; // disable unnecessary WP condition
}
}
add_action( 'pre_get_posts', 'isu_search_url' );
```
Now it works, you don't have to change `.htaccess`, etc.
Pagination will work properly. :)
|
193,369 |
<p>How do I get the authors avatar? Buddypress plugin or any plugin.</p>
<p>I have found this inside my PHP code:</p>
<p><code>"<i class="fa fa-user"></i><span>'.get_the_author().'</span></div>';"</code></p>
<p>It shows a small image before the author's name, I wanted to change the <code>fa fa-user</code> into author's avatar or buddypress avatar.</p>
<p>What will be the script to do that?</p>
|
[
{
"answer_id": 193372,
"author": "lucian",
"author_id": 70333,
"author_profile": "https://wordpress.stackexchange.com/users/70333",
"pm_score": 3,
"selected": false,
"text": "<p>The function you're looking for is <a href=\"https://codex.wordpress.org/Function_Reference/get_avatar\" rel=\"noreferrer\"><code>get_avatar</code></a> - you should put in something like this:</p>\n\n<pre><code><?php echo get_avatar( get_the_author_meta( 'ID' )); ?>\n</code></pre>\n"
},
{
"answer_id": 390398,
"author": "Mohammad Ayoub Khan",
"author_id": 207411,
"author_profile": "https://wordpress.stackexchange.com/users/207411",
"pm_score": 0,
"selected": false,
"text": "<p>There are two methods to get user avatar in WordPress.</p>\n<p><strong>1st Method:</strong></p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\nif (get_the_author_meta('email')) {\n echo get_avatar(get_the_author_meta('email'), '60');\n}\n?>\n</code></pre>\n<p><strong>2nd Method:</strong></p>\n<pre class=\"lang-php prettyprint-override\"><code><?php echo get_avatar(get_the_author_meta('ID')); ?>\n</code></pre>\n<p><strong>3rd Method</strong></p>\n<pre class=\"lang-html prettyprint-override\"><code><picture>\n <source srcset="<?php print get_avatar_url(get_current_user_id(), ['size' => '51']); ?>" media="(min-width: 992px)" />\n <img src="<?php print get_avatar_url(get_current_user_id(), ['size' => '40']); ?>" />\n</picture>\n</code></pre>\n"
}
] |
2015/07/02
|
[
"https://wordpress.stackexchange.com/questions/193369",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
How do I get the authors avatar? Buddypress plugin or any plugin.
I have found this inside my PHP code:
`"<i class="fa fa-user"></i><span>'.get_the_author().'</span></div>';"`
It shows a small image before the author's name, I wanted to change the `fa fa-user` into author's avatar or buddypress avatar.
What will be the script to do that?
|
The function you're looking for is [`get_avatar`](https://codex.wordpress.org/Function_Reference/get_avatar) - you should put in something like this:
```
<?php echo get_avatar( get_the_author_meta( 'ID' )); ?>
```
|
193,390 |
<p>Currently im making new theme and had the idea of adding featured image in the admin side of wordpress, unfortunately its not working this is what i have tried</p>
<p>I have added this code in functions.php</p>
<pre><code>add_theme_support( 'post-thumbnails');
</code></pre>
<p>i also tried to change it </p>
<pre><code>add_theme_support( 'post-thumbnails', array( 'post' ) ); // Add it for posts
add_theme_support( 'post-thumbnails', array( 'page' ) ); // Add it for pages
</code></pre>
<p>after i refresh and log in to my admin panel and tried to create new post or page
featured image is not displaying and </p>
<p>after my set up function which is ja_theme_setup this is my code</p>
<pre><code>add_action('after-setup_theme','ja_theme_setup' );
</code></pre>
<p>and also i have tried to look at <strong>SCREEN OPTIONS</strong> but i dont have any availble checkbox related to featured image..Please help me guys </p>
<p><strong>NOTE:</strong>
My wp-config.php file debug options is set to true</p>
<pre><code>define('WP_DEBUG', true);
</code></pre>
<p>and yet i dont have any errors</p>
|
[
{
"answer_id": 193394,
"author": "shuvroMithun",
"author_id": 65928,
"author_profile": "https://wordpress.stackexchange.com/users/65928",
"pm_score": -1,
"selected": false,
"text": "<p>Your code should work , but as it is not working the try the following things </p>\n\n<pre><code>add_theme_support( 'post-thumbnails');\n</code></pre>\n\n<p>Just put this code in <code>functions.php</code> , not within a function . Just put this code on the top of your <code>functions.php</code> file . If it is not working then try this plugin </p>\n\n<p><a href=\"https://wordpress.org/plugins/drag-drop-featured-image/\" rel=\"nofollow\">Drag & Drop Featured Image</a></p>\n"
},
{
"answer_id": 193396,
"author": "Dinesh Bhimani",
"author_id": 75609,
"author_profile": "https://wordpress.stackexchange.com/users/75609",
"pm_score": 0,
"selected": false,
"text": "<p>You need to go your wp-admin/post/ top right corner show \"<strong>screen Options</strong>\" click on this and</p>\n\n<p>expand screen-option then click on <strong>Featured Image</strong> check box</p>\n\n<p>Hope this help you..</p>\n"
},
{
"answer_id": 193397,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>You have misspelled the action hook name.</p>\n\n<p>This:</p>\n\n<pre><code>add_action( 'after-setup_theme', 'ja_theme_setup' );\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'ja_theme_setup' );\n</code></pre>\n\n<p>The full code:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'ja_theme_setup' );\nfunction ja_theme_setup() {\n add_theme_support( 'post-thumbnails');\n}\n</code></pre>\n"
}
] |
2015/07/03
|
[
"https://wordpress.stackexchange.com/questions/193390",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75608/"
] |
Currently im making new theme and had the idea of adding featured image in the admin side of wordpress, unfortunately its not working this is what i have tried
I have added this code in functions.php
```
add_theme_support( 'post-thumbnails');
```
i also tried to change it
```
add_theme_support( 'post-thumbnails', array( 'post' ) ); // Add it for posts
add_theme_support( 'post-thumbnails', array( 'page' ) ); // Add it for pages
```
after i refresh and log in to my admin panel and tried to create new post or page
featured image is not displaying and
after my set up function which is ja\_theme\_setup this is my code
```
add_action('after-setup_theme','ja_theme_setup' );
```
and also i have tried to look at **SCREEN OPTIONS** but i dont have any availble checkbox related to featured image..Please help me guys
**NOTE:**
My wp-config.php file debug options is set to true
```
define('WP_DEBUG', true);
```
and yet i dont have any errors
|
You have misspelled the action hook name.
This:
```
add_action( 'after-setup_theme', 'ja_theme_setup' );
```
Should be:
```
add_action( 'after_setup_theme', 'ja_theme_setup' );
```
The full code:
```
add_action( 'after_setup_theme', 'ja_theme_setup' );
function ja_theme_setup() {
add_theme_support( 'post-thumbnails');
}
```
|
193,402 |
<p>I've created a CPT in my WordPress site. In this CPT I have the content element (which is the default WP content) and want to make it expandable, I mean, while viewing the CPT I want it to only display a few lines of text until you press the view full content or something similar, all this inside the post view. Like in the image below:</p>
<p><img src="https://i.stack.imgur.com/ZFkML.png" alt="Expandable WordPress content inside a post"></p>
|
[
{
"answer_id": 193394,
"author": "shuvroMithun",
"author_id": 65928,
"author_profile": "https://wordpress.stackexchange.com/users/65928",
"pm_score": -1,
"selected": false,
"text": "<p>Your code should work , but as it is not working the try the following things </p>\n\n<pre><code>add_theme_support( 'post-thumbnails');\n</code></pre>\n\n<p>Just put this code in <code>functions.php</code> , not within a function . Just put this code on the top of your <code>functions.php</code> file . If it is not working then try this plugin </p>\n\n<p><a href=\"https://wordpress.org/plugins/drag-drop-featured-image/\" rel=\"nofollow\">Drag & Drop Featured Image</a></p>\n"
},
{
"answer_id": 193396,
"author": "Dinesh Bhimani",
"author_id": 75609,
"author_profile": "https://wordpress.stackexchange.com/users/75609",
"pm_score": 0,
"selected": false,
"text": "<p>You need to go your wp-admin/post/ top right corner show \"<strong>screen Options</strong>\" click on this and</p>\n\n<p>expand screen-option then click on <strong>Featured Image</strong> check box</p>\n\n<p>Hope this help you..</p>\n"
},
{
"answer_id": 193397,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>You have misspelled the action hook name.</p>\n\n<p>This:</p>\n\n<pre><code>add_action( 'after-setup_theme', 'ja_theme_setup' );\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'ja_theme_setup' );\n</code></pre>\n\n<p>The full code:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'ja_theme_setup' );\nfunction ja_theme_setup() {\n add_theme_support( 'post-thumbnails');\n}\n</code></pre>\n"
}
] |
2015/07/03
|
[
"https://wordpress.stackexchange.com/questions/193402",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60103/"
] |
I've created a CPT in my WordPress site. In this CPT I have the content element (which is the default WP content) and want to make it expandable, I mean, while viewing the CPT I want it to only display a few lines of text until you press the view full content or something similar, all this inside the post view. Like in the image below:

|
You have misspelled the action hook name.
This:
```
add_action( 'after-setup_theme', 'ja_theme_setup' );
```
Should be:
```
add_action( 'after_setup_theme', 'ja_theme_setup' );
```
The full code:
```
add_action( 'after_setup_theme', 'ja_theme_setup' );
function ja_theme_setup() {
add_theme_support( 'post-thumbnails');
}
```
|
193,405 |
<p>I'm using <a href="https://codex.wordpress.org/Template_Tags/get_posts" rel="noreferrer"><code>get_posts()</code></a> like this:</p>
<pre><code>$posts = get_posts(array('orderby' => 'post_status'))
</code></pre>
<p>which is not possible cause it's not in the allowed keys in the <a href="https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/query.php#L2217" rel="noreferrer"><code>parse_orderby()</code></a> method</p>
<p>How to get around this limitation?</p>
|
[
{
"answer_id": 193410,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/hooks/posts_orderby/\"><code>'posts_orderby'</code></a> filter to change the SQL performed.</p>\n\n<p>Note that:</p>\n\n<ul>\n<li>using <code>get_posts()</code> you need to set <code>'suppress_filters'</code> argument of <code>false</code> for the filter to be performed</li>\n<li>if you don't explicitly set <code>'post_status'</code> you'll get only published posts (so no much to order)</li>\n</ul>\n\n<p>Code sample:</p>\n\n<pre><code>$filter = function() {\n return 'post_status ASC';\n};\n\nadd_filter('posts_orderby', $filter);\n\n$posts = get_posts('post_status' => 'any', 'suppress_filters' => false);\n\nremove_filter('posts_orderby', $filter);\n</code></pre>\n"
},
{
"answer_id": 365636,
"author": "iB Arts Pvt Ltd",
"author_id": 187302,
"author_profile": "https://wordpress.stackexchange.com/users/187302",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_filter('posts_orderby', 'custom_post_status', 10,2);\nfunction custom_post_status($args, $wp_query){\n if($wp_query->query_vars['orderby'] == 'post_status') {\n if($wp_query->query_vars['order']) {\n return 'post_status '.$wp_query->query_vars['order'];\n }\n else {\n return 'post_status ASC';\n }\n }\n return $args;\n} \n\n</code></pre>\n\n<p>Adding this would enable 'orderby' => 'post_status' in WP_Query</p>\n"
}
] |
2015/07/03
|
[
"https://wordpress.stackexchange.com/questions/193405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18981/"
] |
I'm using [`get_posts()`](https://codex.wordpress.org/Template_Tags/get_posts) like this:
```
$posts = get_posts(array('orderby' => 'post_status'))
```
which is not possible cause it's not in the allowed keys in the [`parse_orderby()`](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/query.php#L2217) method
How to get around this limitation?
|
You can use [`'posts_orderby'`](https://developer.wordpress.org/reference/hooks/posts_orderby/) filter to change the SQL performed.
Note that:
* using `get_posts()` you need to set `'suppress_filters'` argument of `false` for the filter to be performed
* if you don't explicitly set `'post_status'` you'll get only published posts (so no much to order)
Code sample:
```
$filter = function() {
return 'post_status ASC';
};
add_filter('posts_orderby', $filter);
$posts = get_posts('post_status' => 'any', 'suppress_filters' => false);
remove_filter('posts_orderby', $filter);
```
|
193,436 |
<p>I've got a custom post type, and I'd like to be able to change the preview link but from what I can tell, the hook for preview_post_link only affects the default post type.</p>
<p>Any guidance?</p>
<p>Here's what I've been trying.</p>
<pre><code>add_filter( 'preview_post_link', 'append_preview_query_vars' );
function append_preview_query_vars( $link, $post ) {
if( $post->post_type === "2016program" ) {
return $link . "?program_year=2016";
} else {
return $link;
}
}
</code></pre>
|
[
{
"answer_id": 193446,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<h2>Two problems here:</h2>\n\n<p><strong>#1</strong> </p>\n\n<p>You're missing the <code>$accepted_args</code> argument in:</p>\n\n<pre><code>add_filter( $tag, $callback_function, $priority, $accepted_args );\n</code></pre>\n\n<p>Check out the <a href=\"https://codex.wordpress.org/Function_Reference/add_filter#Parameters\" rel=\"nofollow\">Codex here</a> for more info on that.</p>\n\n<p><strong>#2</strong> </p>\n\n<p>Note that <code>$link . \"?program_year=2016\"</code> is problematic, since it gives us this kind of link:</p>\n\n<pre><code> /?p=123&preview=true?program_year=2016\n</code></pre>\n\n<p>But using instead <code>add_query_arg( [ 'program_year' => '2016' ], $link )</code> we get the correct form:</p>\n\n<pre><code>/?p=123&preview=true&program_year=2016\n</code></pre>\n\n<h2>Updated code snippet:</h2>\n\n<p>Please try this instead (PHP 5.4+):</p>\n\n<pre><code>add_filter( 'preview_post_link', function ( $link, \\WP_Post $post )\n{\n return '2016program' === $post->post_type \n ? add_query_arg( [ 'program_year' => '2016' ], $link ) \n : $link;\n\n }, 10, 2 ); // Notice the number of arguments is 2 for $link and $post\n</code></pre>\n\n<p>where we use <code>add_query_arg()</code> to append the extra GET parameter to the link.</p>\n"
},
{
"answer_id": 194148,
"author": "Matthias Max",
"author_id": 47327,
"author_profile": "https://wordpress.stackexchange.com/users/47327",
"pm_score": 0,
"selected": false,
"text": "<p>Trying @birgire's solution. Is it valid for Wordpress 4.x?</p>\n\n<p>I can't add any fot eh preview_post_link or preview_page_link filters. The function jsut doesn't get hit.</p>\n\n<pre><code>function bitflower_change_post_link($link, $post) {\n\n //replace www part with server1 using the following php function\n //preg_replace ( patter, replace, subject ) syntax\n // $link = preg_replace('/cms/', '', $link);\n $link = $link . '?testttttt=1';\n return $link;\n}\nadd_filter('preview_post_link', 'bitflower_change_post_link', 10, 2);\n</code></pre>\n\n<p>I've tried with the 10,2 parameters and without. I've had a string written to a file to see if the filter gets hit. No luck.</p>\n\n<p>The official code reference of Wordpress does list at least the filter preview_post_link.</p>\n\n<p>Any ideas?</p>\n\n<p>PS: wanted to comment but don't have enough reputation.</p>\n"
}
] |
2015/07/03
|
[
"https://wordpress.stackexchange.com/questions/193436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14828/"
] |
I've got a custom post type, and I'd like to be able to change the preview link but from what I can tell, the hook for preview\_post\_link only affects the default post type.
Any guidance?
Here's what I've been trying.
```
add_filter( 'preview_post_link', 'append_preview_query_vars' );
function append_preview_query_vars( $link, $post ) {
if( $post->post_type === "2016program" ) {
return $link . "?program_year=2016";
} else {
return $link;
}
}
```
|
Two problems here:
------------------
**#1**
You're missing the `$accepted_args` argument in:
```
add_filter( $tag, $callback_function, $priority, $accepted_args );
```
Check out the [Codex here](https://codex.wordpress.org/Function_Reference/add_filter#Parameters) for more info on that.
**#2**
Note that `$link . "?program_year=2016"` is problematic, since it gives us this kind of link:
```
/?p=123&preview=true?program_year=2016
```
But using instead `add_query_arg( [ 'program_year' => '2016' ], $link )` we get the correct form:
```
/?p=123&preview=true&program_year=2016
```
Updated code snippet:
---------------------
Please try this instead (PHP 5.4+):
```
add_filter( 'preview_post_link', function ( $link, \WP_Post $post )
{
return '2016program' === $post->post_type
? add_query_arg( [ 'program_year' => '2016' ], $link )
: $link;
}, 10, 2 ); // Notice the number of arguments is 2 for $link and $post
```
where we use `add_query_arg()` to append the extra GET parameter to the link.
|
193,467 |
<p>Is it possible to redirect a user in WP without the header/wp_redirect being before header()?</p>
<p>I have a plugin that allows users to manage content they have created on the site... for example, they can delete it or disable comments</p>
<p>It's quite basic so i'm just using a GET request.. ie.</p>
<p><code>?action=comments&status=disable</code></p>
<p>When this button is click the action is performed but nothing happens on the page and the url is now: <code>www.domain.com/user_data?action=comments&status=disable</code> what I want to do is on success redirect the user back to <code>www.domain.com/user_data</code></p>
<p>I have tried wp_redirect() and header() but they give 'headers already sent warnings'</p>
<p>I'm not sure how i can put that before the header when this code is within my plugin.</p>
<pre><code> $query = $this->db->update(
//do something
);
if($query == 0)
{
$this->setMessage('error', 'There was an error: ' . $this->db->print_error());
}
else
{
wp_redirect(site_url('/user_data/'));
}
</code></pre>
|
[
{
"answer_id": 193598,
"author": "Goodbytes",
"author_id": 74399,
"author_profile": "https://wordpress.stackexchange.com/users/74399",
"pm_score": 2,
"selected": true,
"text": "<p>It's simply not possible, so here is the work around I come up with</p>\n\n<pre><code> public function redirect($url = false)\n {\n if(headers_sent())\n {\n $destination = ($url == false ? 'location.reload();' : 'window.location.href=\"' . $url . '\";');\n echo die('<script>' . $destination . '</script>');\n }\n else\n {\n $destination = ($url == false ? $_SERVER['REQUEST_URI'] : $url);\n header('Location: ' . $destination);\n die();\n } \n }\n</code></pre>\n"
},
{
"answer_id": 298655,
"author": "frank",
"author_id": 140263,
"author_profile": "https://wordpress.stackexchange.com/users/140263",
"pm_score": 2,
"selected": false,
"text": "<p>It may not be the correct approach, but I found that using wp_loaded does the trick and puts you back in the right spot; you have to set the right conditions to be sure the correct data is being handled. Then strip the url from the conditions before redirecting. Aside from condtions you can also apply capability checks.</p>\n\n<pre><code>add_action ('wp_loaded', 'clean_admin_referer');\nfunction clean_admin_referer() {\n\nif ( isset( $_REQUEST['condition1']) && isset($_REQUEST['condition2']) ) {\n\n if (current_user_can('administrator')) {\n\n <!-- do your database magic -->\n\n $_SERVER['REQUEST_URI'] = remove_query_arg( array( 'condition1', 'condition2' ));\n\n wp_redirect($_SERVER['REQUEST_URI']);\n\n }\n}\n</code></pre>\n"
}
] |
2015/07/03
|
[
"https://wordpress.stackexchange.com/questions/193467",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74399/"
] |
Is it possible to redirect a user in WP without the header/wp\_redirect being before header()?
I have a plugin that allows users to manage content they have created on the site... for example, they can delete it or disable comments
It's quite basic so i'm just using a GET request.. ie.
`?action=comments&status=disable`
When this button is click the action is performed but nothing happens on the page and the url is now: `www.domain.com/user_data?action=comments&status=disable` what I want to do is on success redirect the user back to `www.domain.com/user_data`
I have tried wp\_redirect() and header() but they give 'headers already sent warnings'
I'm not sure how i can put that before the header when this code is within my plugin.
```
$query = $this->db->update(
//do something
);
if($query == 0)
{
$this->setMessage('error', 'There was an error: ' . $this->db->print_error());
}
else
{
wp_redirect(site_url('/user_data/'));
}
```
|
It's simply not possible, so here is the work around I come up with
```
public function redirect($url = false)
{
if(headers_sent())
{
$destination = ($url == false ? 'location.reload();' : 'window.location.href="' . $url . '";');
echo die('<script>' . $destination . '</script>');
}
else
{
$destination = ($url == false ? $_SERVER['REQUEST_URI'] : $url);
header('Location: ' . $destination);
die();
}
}
```
|
193,489 |
<p>I want to add small javascript program in wordpress post, please let me know how to add / execute in WP Post ?</p>
<h2>EDIT</h2>
<p>Yes I tried, but no luck.</p>
<p>First I added HTML Code & JavaScript in Post Text Editor, No Luck,
Then I created Separate JS file & posted only HTML code & called js file using <code><Script src=<Path of the JS File>></code> - No Luck.</p>
|
[
{
"answer_id": 193490,
"author": "Carl Willis",
"author_id": 69413,
"author_profile": "https://wordpress.stackexchange.com/users/69413",
"pm_score": 0,
"selected": false,
"text": "<p>You can add your script on header or footer normally with .\nOr you can hooked your script on function.php like this way:</p>\n\n<pre><code>function theme_name_scripts() {\nwp_enqueue_style( 'style-name', get_stylesheet_uri() );\nwp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'theme_name_scripts' );\n</code></pre>\n"
},
{
"answer_id": 193491,
"author": "Jeremy",
"author_id": 73884,
"author_profile": "https://wordpress.stackexchange.com/users/73884",
"pm_score": 0,
"selected": false,
"text": "<p>If it is for all the posts, an external script is always a better idea, linked with <code>wp_enqueue_script()</code> (see <a href=\"http://www.sitepoint.com/including-javascript-in-plugins-or-themes/\" rel=\"nofollow\">this article</a> for more information).</p>\n\n<p>If you only want to add a code to a single post, simply write it in the editor (into a <code>script</code> tag, in the \"Text\" tab).</p>\n"
},
{
"answer_id": 193544,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 0,
"selected": false,
"text": "<p>If you go in and edit the post, and click the \"Text\" tab, and enter your code in <code><script></code> tags:</p>\n\n<pre><code><script type=\"text/javascript\">\nconsole.log(\"gosh\");\n</script>\n</code></pre>\n\n<p>and update the post, the content should save as</p>\n\n<pre><code><script type=\"text/javascript\">// <![CDATA[\nconsole.log(\"gosh\");\n// ]]></script>\n</code></pre>\n\n<p>which should execute when the post is viewed.</p>\n"
},
{
"answer_id": 193565,
"author": "marcovega",
"author_id": 14225,
"author_profile": "https://wordpress.stackexchange.com/users/14225",
"pm_score": 1,
"selected": false,
"text": "<p>One option would be to create a shortcode exclusively for that script. Even thought it's not an elegant solution, it works. In your functions file (functions.php) of your theme add:</p>\n\n<pre><code>function custom_script_shortcode(){\n $code = '<script>';\n $code .= 'var foo = \"bar\";'\n $code .= '</script>';\n return $code;\n}\nadd_shortcode(\"custom_script_shortcode\", \"custom_script\");\n</code></pre>\n\n<p>And in your post editor then add the shortcode:</p>\n\n<pre><code>[custom_script]\n</code></pre>\n\n<p>Just be careful when you assign your JavaScript to the variable $code so you don't close the string with \" or '</p>\n"
}
] |
2015/07/04
|
[
"https://wordpress.stackexchange.com/questions/193489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75652/"
] |
I want to add small javascript program in wordpress post, please let me know how to add / execute in WP Post ?
EDIT
----
Yes I tried, but no luck.
First I added HTML Code & JavaScript in Post Text Editor, No Luck,
Then I created Separate JS file & posted only HTML code & called js file using `<Script src=<Path of the JS File>>` - No Luck.
|
One option would be to create a shortcode exclusively for that script. Even thought it's not an elegant solution, it works. In your functions file (functions.php) of your theme add:
```
function custom_script_shortcode(){
$code = '<script>';
$code .= 'var foo = "bar";'
$code .= '</script>';
return $code;
}
add_shortcode("custom_script_shortcode", "custom_script");
```
And in your post editor then add the shortcode:
```
[custom_script]
```
Just be careful when you assign your JavaScript to the variable $code so you don't close the string with " or '
|
193,495 |
<p>How to change the username with <a href="http://wp-cli.org" rel="noreferrer">wp-cli</a>?</p>
<p>This does not work:</p>
<pre><code>wp user update old_login --user-login=new_login
</code></pre>
|
[
{
"answer_id": 193496,
"author": "the",
"author_id": 44793,
"author_profile": "https://wordpress.stackexchange.com/users/44793",
"pm_score": 3,
"selected": false,
"text": "<p><code>search-replace</code> does the trick but can have undesired side effects if <code>old_login</code> appears in other contexts in the database:</p>\n\n<pre><code>wp search-replace old_login new_login\n</code></pre>\n\n<p>But before doing that run</p>\n\n<pre><code>wp sql dump\nwp search-replace old_login new_login --dry-run\n</code></pre>\n\n<p>To make an SQL dump and see what is going to be replaced.</p>\n"
},
{
"answer_id": 193504,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<h2>Not allowed by design:</h2>\n\n<p>If we try to change the user login by the email:</p>\n\n<pre><code>wp user update [email protected] --user_login=mary_new\n</code></pre>\n\n<p>or by the user id:</p>\n\n<pre><code>wp user update 123 --user_login=mary_new\n</code></pre>\n\n<p>we get the following warning:</p>\n\n<blockquote>\n <p>User logins can't be changed.</p>\n</blockquote>\n\n<p>This is the reason:</p>\n\n<pre><code>if ( isset( $assoc_args['user_login'] ) ) {\n WP_CLI::warning( \"User logins can't be changed.\" );\n unset( $assoc_args['user_login'] );\n}\n</code></pre>\n\n<p>within the <code>user</code> <code>update</code> <a href=\"https://github.com/wp-cli/wp-cli/blob/becebdc58cbc2e5caabee6ebfc111d0de44f423e/php/commands/user.php#L340-L343\" rel=\"noreferrer\">method</a>. </p>\n\n<h2>Possible workarounds:</h2>\n\n<p><strong>Custom SQL queries:</strong></p>\n\n<p>If we only want to target the <code>wp_users</code> table and the <code>user_login</code> field, it's possible to run the SQL query with:</p>\n\n<pre><code>wp db query \"UPDATE wp_users SET user_login = 'mary_new' WHERE user_login = 'mary'\"\n</code></pre>\n\n<p>But we have to make sure the user logins are <strong>unique</strong>.</p>\n\n<p>I experiented with this kind of query:</p>\n\n<pre><code>wp db query \"UPDATE wp_users u, \n ( SELECT \n COUNT(*) as number_of_same_login_users\n FROM wp_users u \n WHERE user_login = 'mary_new' \n ) tmp \n SET u.user_login = 'mary_new' \n WHERE \n u.user_login = 'mary_old' \n AND tmp.number_of_same_login_users = 0\"\n</code></pre>\n\n<p>to enforce the uniqueness of the <code>user_login</code> field, by only updating, if the no user has the same user login name.</p>\n\n<p><a href=\"https://stackoverflow.com/a/18153569/2078474\">This unrelated answer</a> helped me constructing an UPDATE with a subquery.</p>\n\n<p>Here's the same command in a single line:</p>\n\n<pre><code>wp db query \"UPDATE wp_users u, ( SELECT COUNT(*) as number_of_same_login_users FROM wp_users WHERE user_login = 'mary_new' ) tmp SET u.user_login = 'mary_new' WHERE u.user_login = 'mary_old' AND tmp.number_of_same_login_users = 0\"\n</code></pre>\n\n<p>but this is kind of query should be inside a custom command ;-)</p>\n\n<p>Note that the table prefix might be different than <code>wp_</code>.</p>\n\n<p><strong>Custom WP-CLI commands:</strong></p>\n\n<p>Like explained in the <a href=\"https://github.com/wp-cli/wp-cli/wiki/Commands-Cookbook\" rel=\"noreferrer\">Commands Cookbook</a>, it's possible to create custom WP-CLI commands.</p>\n\n<p>We might try to build a custom command like:</p>\n\n<pre><code> WP_CLI::add_command( 'wpse_replace_user_login', 'WPSE_Replace_User_Login' );\n</code></pre>\n\n<p>or:</p>\n\n<pre><code> WP_CLI::add_command( 'wpse_user', 'WPSE_User_Command' );\n</code></pre>\n\n<p>where <code>WPSE_User_Command</code> extends the <code>User_Command</code> class. This would need further work.</p>\n"
}
] |
2015/07/04
|
[
"https://wordpress.stackexchange.com/questions/193495",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44793/"
] |
How to change the username with [wp-cli](http://wp-cli.org)?
This does not work:
```
wp user update old_login --user-login=new_login
```
|
Not allowed by design:
----------------------
If we try to change the user login by the email:
```
wp user update [email protected] --user_login=mary_new
```
or by the user id:
```
wp user update 123 --user_login=mary_new
```
we get the following warning:
>
> User logins can't be changed.
>
>
>
This is the reason:
```
if ( isset( $assoc_args['user_login'] ) ) {
WP_CLI::warning( "User logins can't be changed." );
unset( $assoc_args['user_login'] );
}
```
within the `user` `update` [method](https://github.com/wp-cli/wp-cli/blob/becebdc58cbc2e5caabee6ebfc111d0de44f423e/php/commands/user.php#L340-L343).
Possible workarounds:
---------------------
**Custom SQL queries:**
If we only want to target the `wp_users` table and the `user_login` field, it's possible to run the SQL query with:
```
wp db query "UPDATE wp_users SET user_login = 'mary_new' WHERE user_login = 'mary'"
```
But we have to make sure the user logins are **unique**.
I experiented with this kind of query:
```
wp db query "UPDATE wp_users u,
( SELECT
COUNT(*) as number_of_same_login_users
FROM wp_users u
WHERE user_login = 'mary_new'
) tmp
SET u.user_login = 'mary_new'
WHERE
u.user_login = 'mary_old'
AND tmp.number_of_same_login_users = 0"
```
to enforce the uniqueness of the `user_login` field, by only updating, if the no user has the same user login name.
[This unrelated answer](https://stackoverflow.com/a/18153569/2078474) helped me constructing an UPDATE with a subquery.
Here's the same command in a single line:
```
wp db query "UPDATE wp_users u, ( SELECT COUNT(*) as number_of_same_login_users FROM wp_users WHERE user_login = 'mary_new' ) tmp SET u.user_login = 'mary_new' WHERE u.user_login = 'mary_old' AND tmp.number_of_same_login_users = 0"
```
but this is kind of query should be inside a custom command ;-)
Note that the table prefix might be different than `wp_`.
**Custom WP-CLI commands:**
Like explained in the [Commands Cookbook](https://github.com/wp-cli/wp-cli/wiki/Commands-Cookbook), it's possible to create custom WP-CLI commands.
We might try to build a custom command like:
```
WP_CLI::add_command( 'wpse_replace_user_login', 'WPSE_Replace_User_Login' );
```
or:
```
WP_CLI::add_command( 'wpse_user', 'WPSE_User_Command' );
```
where `WPSE_User_Command` extends the `User_Command` class. This would need further work.
|
193,566 |
<p>I'm struggling with this one and all of the relevant links to the codex, articles and forum posts (stack or otherwise) that I've searched haven't helped.</p>
<p>I can best describe my problem as attempting to replicate the native "Add New User" Wordpress functionality. I.e. render a form from an admin page, insert a new record from this form (the equivalent of adding a new user) and update the table.</p>
<p>So far I have: </p>
<p><img src="https://i.stack.imgur.com/xTwWW.jpg" alt="Add Episodes Form"></p>
<p>The plugin code so far looks like:</p>
<pre><code><?php
/*
Plugin Name: Episodes
Description: The episodes plugin
Author: Nick Courage
Version: 1.0
*/
function activate_episodes(){
global $wpdb;
$table_name = $wpdb->prefix . 'episodes';
if($wpdb->get_var('SHOW TABLES LIKE' . $table_name) != $table_name){
$sql = 'CREATE TABLE ' . $table_name . '(
episode_id INT NOT NULL AUTO_INCREMENT,
episode_title VARCHAR(45) NOT NULL,
episode_desc VARCHAR(45) NOT NULL,
air_date DATE NOT NULL,
img_url VARCHAR(255) NOT NULL,
PRIMARY KEY (episode_id)
)';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
add_option('episode_database_version', '1.0');
}
}
register_activation_hook(__FILE__,'activate_episodes');
function episodes_add_page(){
?>
<h1>Add Episodes</h1>
<form method="$_POST" action="">
<label for="episode_title">Episode Title:</label>
<input type="text" name="episode_title" id="episode_title" />
<label for="episode_desc">Episode Description:</label>
<input type="text" name="episode_desc" id="episode_desc" />
<label for="air_date">Air date:</label>
<input type="text" name="air_date" id="air_date" />
<input type="submit" value="Submit"/>
</form>
<?php
}
function episodes_plugin_menu(){
add_menu_page('Episodes Page', 'Episodes', 'manage_options','episodes-plugin','episodes_add_page');
}
add_action('admin_menu','episodes_plugin_menu');
function add_episode(){
global $wpdb;
$table_name = $wpdb->prefix . 'episodes';
$wpdb->insert($table_name, array('episode_title'=>$_POST['episode_title'],
'episode_desc'=>$POST['episode_desc'],
'air_date'=>$_POST['air_date'],
'img_url'=>$_POST['img_url']
)
);
}
?>
</code></pre>
|
[
{
"answer_id": 193496,
"author": "the",
"author_id": 44793,
"author_profile": "https://wordpress.stackexchange.com/users/44793",
"pm_score": 3,
"selected": false,
"text": "<p><code>search-replace</code> does the trick but can have undesired side effects if <code>old_login</code> appears in other contexts in the database:</p>\n\n<pre><code>wp search-replace old_login new_login\n</code></pre>\n\n<p>But before doing that run</p>\n\n<pre><code>wp sql dump\nwp search-replace old_login new_login --dry-run\n</code></pre>\n\n<p>To make an SQL dump and see what is going to be replaced.</p>\n"
},
{
"answer_id": 193504,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<h2>Not allowed by design:</h2>\n\n<p>If we try to change the user login by the email:</p>\n\n<pre><code>wp user update [email protected] --user_login=mary_new\n</code></pre>\n\n<p>or by the user id:</p>\n\n<pre><code>wp user update 123 --user_login=mary_new\n</code></pre>\n\n<p>we get the following warning:</p>\n\n<blockquote>\n <p>User logins can't be changed.</p>\n</blockquote>\n\n<p>This is the reason:</p>\n\n<pre><code>if ( isset( $assoc_args['user_login'] ) ) {\n WP_CLI::warning( \"User logins can't be changed.\" );\n unset( $assoc_args['user_login'] );\n}\n</code></pre>\n\n<p>within the <code>user</code> <code>update</code> <a href=\"https://github.com/wp-cli/wp-cli/blob/becebdc58cbc2e5caabee6ebfc111d0de44f423e/php/commands/user.php#L340-L343\" rel=\"noreferrer\">method</a>. </p>\n\n<h2>Possible workarounds:</h2>\n\n<p><strong>Custom SQL queries:</strong></p>\n\n<p>If we only want to target the <code>wp_users</code> table and the <code>user_login</code> field, it's possible to run the SQL query with:</p>\n\n<pre><code>wp db query \"UPDATE wp_users SET user_login = 'mary_new' WHERE user_login = 'mary'\"\n</code></pre>\n\n<p>But we have to make sure the user logins are <strong>unique</strong>.</p>\n\n<p>I experiented with this kind of query:</p>\n\n<pre><code>wp db query \"UPDATE wp_users u, \n ( SELECT \n COUNT(*) as number_of_same_login_users\n FROM wp_users u \n WHERE user_login = 'mary_new' \n ) tmp \n SET u.user_login = 'mary_new' \n WHERE \n u.user_login = 'mary_old' \n AND tmp.number_of_same_login_users = 0\"\n</code></pre>\n\n<p>to enforce the uniqueness of the <code>user_login</code> field, by only updating, if the no user has the same user login name.</p>\n\n<p><a href=\"https://stackoverflow.com/a/18153569/2078474\">This unrelated answer</a> helped me constructing an UPDATE with a subquery.</p>\n\n<p>Here's the same command in a single line:</p>\n\n<pre><code>wp db query \"UPDATE wp_users u, ( SELECT COUNT(*) as number_of_same_login_users FROM wp_users WHERE user_login = 'mary_new' ) tmp SET u.user_login = 'mary_new' WHERE u.user_login = 'mary_old' AND tmp.number_of_same_login_users = 0\"\n</code></pre>\n\n<p>but this is kind of query should be inside a custom command ;-)</p>\n\n<p>Note that the table prefix might be different than <code>wp_</code>.</p>\n\n<p><strong>Custom WP-CLI commands:</strong></p>\n\n<p>Like explained in the <a href=\"https://github.com/wp-cli/wp-cli/wiki/Commands-Cookbook\" rel=\"noreferrer\">Commands Cookbook</a>, it's possible to create custom WP-CLI commands.</p>\n\n<p>We might try to build a custom command like:</p>\n\n<pre><code> WP_CLI::add_command( 'wpse_replace_user_login', 'WPSE_Replace_User_Login' );\n</code></pre>\n\n<p>or:</p>\n\n<pre><code> WP_CLI::add_command( 'wpse_user', 'WPSE_User_Command' );\n</code></pre>\n\n<p>where <code>WPSE_User_Command</code> extends the <code>User_Command</code> class. This would need further work.</p>\n"
}
] |
2015/07/05
|
[
"https://wordpress.stackexchange.com/questions/193566",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75694/"
] |
I'm struggling with this one and all of the relevant links to the codex, articles and forum posts (stack or otherwise) that I've searched haven't helped.
I can best describe my problem as attempting to replicate the native "Add New User" Wordpress functionality. I.e. render a form from an admin page, insert a new record from this form (the equivalent of adding a new user) and update the table.
So far I have:

The plugin code so far looks like:
```
<?php
/*
Plugin Name: Episodes
Description: The episodes plugin
Author: Nick Courage
Version: 1.0
*/
function activate_episodes(){
global $wpdb;
$table_name = $wpdb->prefix . 'episodes';
if($wpdb->get_var('SHOW TABLES LIKE' . $table_name) != $table_name){
$sql = 'CREATE TABLE ' . $table_name . '(
episode_id INT NOT NULL AUTO_INCREMENT,
episode_title VARCHAR(45) NOT NULL,
episode_desc VARCHAR(45) NOT NULL,
air_date DATE NOT NULL,
img_url VARCHAR(255) NOT NULL,
PRIMARY KEY (episode_id)
)';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
add_option('episode_database_version', '1.0');
}
}
register_activation_hook(__FILE__,'activate_episodes');
function episodes_add_page(){
?>
<h1>Add Episodes</h1>
<form method="$_POST" action="">
<label for="episode_title">Episode Title:</label>
<input type="text" name="episode_title" id="episode_title" />
<label for="episode_desc">Episode Description:</label>
<input type="text" name="episode_desc" id="episode_desc" />
<label for="air_date">Air date:</label>
<input type="text" name="air_date" id="air_date" />
<input type="submit" value="Submit"/>
</form>
<?php
}
function episodes_plugin_menu(){
add_menu_page('Episodes Page', 'Episodes', 'manage_options','episodes-plugin','episodes_add_page');
}
add_action('admin_menu','episodes_plugin_menu');
function add_episode(){
global $wpdb;
$table_name = $wpdb->prefix . 'episodes';
$wpdb->insert($table_name, array('episode_title'=>$_POST['episode_title'],
'episode_desc'=>$POST['episode_desc'],
'air_date'=>$_POST['air_date'],
'img_url'=>$_POST['img_url']
)
);
}
?>
```
|
Not allowed by design:
----------------------
If we try to change the user login by the email:
```
wp user update [email protected] --user_login=mary_new
```
or by the user id:
```
wp user update 123 --user_login=mary_new
```
we get the following warning:
>
> User logins can't be changed.
>
>
>
This is the reason:
```
if ( isset( $assoc_args['user_login'] ) ) {
WP_CLI::warning( "User logins can't be changed." );
unset( $assoc_args['user_login'] );
}
```
within the `user` `update` [method](https://github.com/wp-cli/wp-cli/blob/becebdc58cbc2e5caabee6ebfc111d0de44f423e/php/commands/user.php#L340-L343).
Possible workarounds:
---------------------
**Custom SQL queries:**
If we only want to target the `wp_users` table and the `user_login` field, it's possible to run the SQL query with:
```
wp db query "UPDATE wp_users SET user_login = 'mary_new' WHERE user_login = 'mary'"
```
But we have to make sure the user logins are **unique**.
I experiented with this kind of query:
```
wp db query "UPDATE wp_users u,
( SELECT
COUNT(*) as number_of_same_login_users
FROM wp_users u
WHERE user_login = 'mary_new'
) tmp
SET u.user_login = 'mary_new'
WHERE
u.user_login = 'mary_old'
AND tmp.number_of_same_login_users = 0"
```
to enforce the uniqueness of the `user_login` field, by only updating, if the no user has the same user login name.
[This unrelated answer](https://stackoverflow.com/a/18153569/2078474) helped me constructing an UPDATE with a subquery.
Here's the same command in a single line:
```
wp db query "UPDATE wp_users u, ( SELECT COUNT(*) as number_of_same_login_users FROM wp_users WHERE user_login = 'mary_new' ) tmp SET u.user_login = 'mary_new' WHERE u.user_login = 'mary_old' AND tmp.number_of_same_login_users = 0"
```
but this is kind of query should be inside a custom command ;-)
Note that the table prefix might be different than `wp_`.
**Custom WP-CLI commands:**
Like explained in the [Commands Cookbook](https://github.com/wp-cli/wp-cli/wiki/Commands-Cookbook), it's possible to create custom WP-CLI commands.
We might try to build a custom command like:
```
WP_CLI::add_command( 'wpse_replace_user_login', 'WPSE_Replace_User_Login' );
```
or:
```
WP_CLI::add_command( 'wpse_user', 'WPSE_User_Command' );
```
where `WPSE_User_Command` extends the `User_Command` class. This would need further work.
|
193,636 |
<p>I use following code to display page in a index.php file of template but doesn't show page content.</p>
<pre><code><?php
$parent_page_content = get_the_content(1677);///my_page_id
echo $parent_page_content;
?>
</code></pre>
|
[
{
"answer_id": 193638,
"author": "Anand",
"author_id": 75715,
"author_profile": "https://wordpress.stackexchange.com/users/75715",
"pm_score": -1,
"selected": false,
"text": "<p>Need to modify in code : </p>\n\n<pre><code><?php\n$post_1677 = get_post(1677); \n$contents = $post_1677->post_content;\necho $contents;\n?>\n</code></pre>\n"
},
{
"answer_id": 193642,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<pre><code>get_the_content( $more_link_text, $stripteaser )\n</code></pre>\n\n<p><code>get_the_content</code> does not take a post ID as a parameter, it always refers to the current post.</p>\n\n<p>Also, don't use magic numbers or hardcode post IDs into your theme, it will break after an import/export or migration.</p>\n\n<p>Instead use <code>get_page_by_title</code>, which is not as bad:</p>\n\n<pre><code>// get the post\n$post = get_page_by_title('page or post title', OBJECT, 'post' );\n// filter its content\n$content = apply_filter('the_content', $post->post_content );\n// display it\necho $content;\n</code></pre>\n"
},
{
"answer_id": 338665,
"author": "Ben Llewellyn",
"author_id": 168721,
"author_profile": "https://wordpress.stackexchange.com/users/168721",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$id = get_the_ID();\n$post = get_post( $id );\necho $output = apply_filters( 'the_content', $post->post_content );\n</code></pre>\n"
}
] |
2015/07/06
|
[
"https://wordpress.stackexchange.com/questions/193636",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67821/"
] |
I use following code to display page in a index.php file of template but doesn't show page content.
```
<?php
$parent_page_content = get_the_content(1677);///my_page_id
echo $parent_page_content;
?>
```
|
```
get_the_content( $more_link_text, $stripteaser )
```
`get_the_content` does not take a post ID as a parameter, it always refers to the current post.
Also, don't use magic numbers or hardcode post IDs into your theme, it will break after an import/export or migration.
Instead use `get_page_by_title`, which is not as bad:
```
// get the post
$post = get_page_by_title('page or post title', OBJECT, 'post' );
// filter its content
$content = apply_filter('the_content', $post->post_content );
// display it
echo $content;
```
|
193,641 |
<p>It doesn't seem that output buffering takes into account echo's from within hooked functions. </p>
<pre><code>function buffer_start() { ob_start(); }
function buffer_end() { ob_end_flush(); }
add_action('init', 'buffer_start');
add_action('admin_footer', 'buffer_end');
add_action("draft_to_publish", "my_hooked_function", 10, 1); // the hook
function my_hooked_function($post) {
echo("<script>console.log('some stuff I want to output to the developer console, via the html page');</script>");
}
</code></pre>
<p>Somehow, this doesn't work. It will ignore the echo, and not update the source on the page. Even though the Wordpress execution cycle is: <code>init</code>, <code>draft_to_publish</code>, <code>admin_footer</code>.</p>
<p>If I input echo's into the buffer_start and buffer_end functions, it works as normal though.</p>
<p>What am I doing wrong? Is there any scope or context or something that I need to reference from within <code>my_hooked_function</code> to make sure the echo there goes to the page's output buffer?</p>
<p>I used this code as a starting point: <a href="http://www.dagondesign.com/articles/wordpress-hook-for-entire-page-using-output-buffering/" rel="nofollow">http://www.dagondesign.com/articles/wordpress-hook-for-entire-page-using-output-buffering/</a></p>
|
[
{
"answer_id": 193646,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 0,
"selected": false,
"text": "<p>Try to simply use ob in your function like so:</p>\n\n<pre><code>add_action( 'draft_to_publish', 'my_hooked_function', 10, 10 );\nfunction my_hooked_function( $post ) {\n ob_start();\n echo '<script>console.log(\"some stuff to output to the developer console, via html page\");</script>';\n $output = ob_get_contents(); // Put ob content in a variable\n $ob_end_clean();\n echo $output; // Echo the variable\n}\n</code></pre>\n\n<p>And I think it's better than add ob_start/en_flush on the full admin.</p>\n"
},
{
"answer_id": 193669,
"author": "Magne",
"author_id": 71131,
"author_profile": "https://wordpress.stackexchange.com/users/71131",
"pm_score": 1,
"selected": false,
"text": "<p>TL;DR: After the <code>draft_to_publish</code> hook is executed, the page is redirected, so you won't see the echoed output.</p>\n\n<p>Ref: <a href=\"https://wordpress.stackexchange.com/a/94011/71131\">https://wordpress.stackexchange.com/a/94011/71131</a></p>\n\n<p>I think the problem is that the draft_to_publish action saves the post, which will call a <code>redirect</code> request to the browser, which loads the edit page from scratch again. Then whatever whatever scripts previously echoed at the bottom of page wouldn't be included, as those were executed on the last page just instants before the redirect took place. </p>\n\n<p>The solution should be to use a proper debug tool to output the echo's to the javascript console. See: <a href=\"https://github.com/nekojira/wp-php-console\" rel=\"nofollow noreferrer\">https://github.com/nekojira/wp-php-console</a></p>\n"
}
] |
2015/07/06
|
[
"https://wordpress.stackexchange.com/questions/193641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71131/"
] |
It doesn't seem that output buffering takes into account echo's from within hooked functions.
```
function buffer_start() { ob_start(); }
function buffer_end() { ob_end_flush(); }
add_action('init', 'buffer_start');
add_action('admin_footer', 'buffer_end');
add_action("draft_to_publish", "my_hooked_function", 10, 1); // the hook
function my_hooked_function($post) {
echo("<script>console.log('some stuff I want to output to the developer console, via the html page');</script>");
}
```
Somehow, this doesn't work. It will ignore the echo, and not update the source on the page. Even though the Wordpress execution cycle is: `init`, `draft_to_publish`, `admin_footer`.
If I input echo's into the buffer\_start and buffer\_end functions, it works as normal though.
What am I doing wrong? Is there any scope or context or something that I need to reference from within `my_hooked_function` to make sure the echo there goes to the page's output buffer?
I used this code as a starting point: <http://www.dagondesign.com/articles/wordpress-hook-for-entire-page-using-output-buffering/>
|
TL;DR: After the `draft_to_publish` hook is executed, the page is redirected, so you won't see the echoed output.
Ref: <https://wordpress.stackexchange.com/a/94011/71131>
I think the problem is that the draft\_to\_publish action saves the post, which will call a `redirect` request to the browser, which loads the edit page from scratch again. Then whatever whatever scripts previously echoed at the bottom of page wouldn't be included, as those were executed on the last page just instants before the redirect took place.
The solution should be to use a proper debug tool to output the echo's to the javascript console. See: <https://github.com/nekojira/wp-php-console>
|
193,643 |
<p>I am trying to set the title tag for Woocommerce pages that have endpoints. I am using Yoast SEO and so far have created this:</p>
<pre><code>function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
return $title;
}
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
</code></pre>
<p>This works, but only for the endpoint pages, all other pages now don't have a title. How can I make my above code return the default title when not on an endpoint page?</p>
<p>Cheers,</p>
<p>Steve</p>
|
[
{
"answer_id": 193655,
"author": "Steve-ACET",
"author_id": 66113,
"author_profile": "https://wordpress.stackexchange.com/users/66113",
"pm_score": 2,
"selected": true,
"text": "<p>It turns out I just needed to return the $title variable which already had what I needed:</p>\n\n<pre><code>function woocommerce_endpoint_titles( $title ) {\n $sep = ' | ';\n $sitetitle = get_bloginfo();\n\n if ( is_wc_endpoint_url( 'view-order' ) ) {\n $title = 'View Order: ' . $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-account' ) ) {\n $title = 'Edit Account'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-address' ) ) {\n $title = 'Edit Address'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'lost-password' ) ) {\n $title = 'Lost Password'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'customer-logout' ) ) {\n $title = 'Logout'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-pay' ) ) {\n $title = 'Order Payment'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-received' ) ) {\n $title = 'Order Received'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'add-payment-method' ) ) {\n $title = 'Add Payment Method'. $sep . $sitetitle; \n }\n return $title;\n}\nadd_filter( 'wpseo_title','woocommerce_endpoint_titles');\n</code></pre>\n"
},
{
"answer_id": 336585,
"author": "rosie",
"author_id": 164849,
"author_profile": "https://wordpress.stackexchange.com/users/164849",
"pm_score": 2,
"selected": false,
"text": "<p>If you added custom WC endpoints on init, you can use something like this instead to check for endpoints (adjust accordingly if you're using Yoast):</p>\n\n<pre><code>function add_custom_endpoints_to_title( $post_title ) {\n\n if ( ! is_account_page() ) {\n return $post_title;\n }\n\n global $wp;\n\n if ( isset( $wp->query_vars['custom_endpoint_1'] ) ) {\n $post_title = 'Custom Endpoint 1';\n } elseif ( isset( $wp->query_vars['custom_endpoint_2'] ) ) {\n $post_title = 'Custom Endpoint 2';\n }\n\n return $post_title;\n}\n\nadd_filter( 'single_post_title', 'add_custom_endpoints_to_title', 99 );\n</code></pre>\n"
}
] |
2015/07/06
|
[
"https://wordpress.stackexchange.com/questions/193643",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66113/"
] |
I am trying to set the title tag for Woocommerce pages that have endpoints. I am using Yoast SEO and so far have created this:
```
function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
return $title;
}
else if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
return $title;
}
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
```
This works, but only for the endpoint pages, all other pages now don't have a title. How can I make my above code return the default title when not on an endpoint page?
Cheers,
Steve
|
It turns out I just needed to return the $title variable which already had what I needed:
```
function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order: ' . $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
}
return $title;
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
```
|
193,683 |
<p>I have added the Open Graph meta data to my <strong>functions.php</strong>:</p>
<pre><code>function insert_fb_in_head() {
global $post;
if ( !is_singular())
return;
echo '<meta property="fb:admins" content="PAGE_ID"/>';
echo '<meta property="og:title" content="' . get_the_title() . '"/>';
echo '<meta property="og:type" content="article"/>';
echo '<meta property="og:url" content="' . get_permalink() . '"/>';
echo '<meta property="og:site_name" content="SITE_TITLE"/>';
echo '<meta property="og:image" content="' . $default_image . '"/>';
}
add_action( 'wp_head', 'insert_fb_in_head', 5 );
</code></pre>
<p>However when pasting from HTTPS, it does not fetch the OG data. Sharing from HTTP works perfectly fine.</p>
<p>I also tried adding:</p>
<pre><code>og:image:secure_url
</code></pre>
<p>Didn't work either.</p>
<p><img src="https://i.imgur.com/kY4fyu0.jpg" alt="HTTP vs HTTPS LinkedIn Share"></p>
|
[
{
"answer_id": 193655,
"author": "Steve-ACET",
"author_id": 66113,
"author_profile": "https://wordpress.stackexchange.com/users/66113",
"pm_score": 2,
"selected": true,
"text": "<p>It turns out I just needed to return the $title variable which already had what I needed:</p>\n\n<pre><code>function woocommerce_endpoint_titles( $title ) {\n $sep = ' | ';\n $sitetitle = get_bloginfo();\n\n if ( is_wc_endpoint_url( 'view-order' ) ) {\n $title = 'View Order: ' . $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-account' ) ) {\n $title = 'Edit Account'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-address' ) ) {\n $title = 'Edit Address'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'lost-password' ) ) {\n $title = 'Lost Password'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'customer-logout' ) ) {\n $title = 'Logout'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-pay' ) ) {\n $title = 'Order Payment'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-received' ) ) {\n $title = 'Order Received'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'add-payment-method' ) ) {\n $title = 'Add Payment Method'. $sep . $sitetitle; \n }\n return $title;\n}\nadd_filter( 'wpseo_title','woocommerce_endpoint_titles');\n</code></pre>\n"
},
{
"answer_id": 336585,
"author": "rosie",
"author_id": 164849,
"author_profile": "https://wordpress.stackexchange.com/users/164849",
"pm_score": 2,
"selected": false,
"text": "<p>If you added custom WC endpoints on init, you can use something like this instead to check for endpoints (adjust accordingly if you're using Yoast):</p>\n\n<pre><code>function add_custom_endpoints_to_title( $post_title ) {\n\n if ( ! is_account_page() ) {\n return $post_title;\n }\n\n global $wp;\n\n if ( isset( $wp->query_vars['custom_endpoint_1'] ) ) {\n $post_title = 'Custom Endpoint 1';\n } elseif ( isset( $wp->query_vars['custom_endpoint_2'] ) ) {\n $post_title = 'Custom Endpoint 2';\n }\n\n return $post_title;\n}\n\nadd_filter( 'single_post_title', 'add_custom_endpoints_to_title', 99 );\n</code></pre>\n"
}
] |
2015/07/06
|
[
"https://wordpress.stackexchange.com/questions/193683",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75598/"
] |
I have added the Open Graph meta data to my **functions.php**:
```
function insert_fb_in_head() {
global $post;
if ( !is_singular())
return;
echo '<meta property="fb:admins" content="PAGE_ID"/>';
echo '<meta property="og:title" content="' . get_the_title() . '"/>';
echo '<meta property="og:type" content="article"/>';
echo '<meta property="og:url" content="' . get_permalink() . '"/>';
echo '<meta property="og:site_name" content="SITE_TITLE"/>';
echo '<meta property="og:image" content="' . $default_image . '"/>';
}
add_action( 'wp_head', 'insert_fb_in_head', 5 );
```
However when pasting from HTTPS, it does not fetch the OG data. Sharing from HTTP works perfectly fine.
I also tried adding:
```
og:image:secure_url
```
Didn't work either.

|
It turns out I just needed to return the $title variable which already had what I needed:
```
function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order: ' . $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
}
return $title;
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
```
|
193,695 |
<p>I use the add_menu_page function in my custom theme builds but when I export my local copy of the site and import it in the production site some of post id numbers change and I have to update this function manually (ie: in the code below: <strong><em>?post=8, ?post=8, ?post=10</em></strong>). Is there a way to have these numbers be dynamic?</p>
<pre><code>function custom_admin_menu_links() {
$user = wp_get_current_user();
if ( ! $user->has_cap( 'manage_options' ) ) {
add_menu_page( 'Home', 'Home', 'edit_posts', 'post.php?post=6&action=edit', '', 'dashicons-admin-home', 1);
add_menu_page( 'About', 'About', 'edit_posts', 'post.php?post=8&action=edit', '', 'dashicons-id', 2);
add_menu_page( 'Contact', 'Contact', 'edit_posts', 'post.php?post=10&action=edit', '', 'dashicons-phone', 3);
}
}
add_action( 'admin_menu', 'custom_admin_menu_links' );
</code></pre>
|
[
{
"answer_id": 193655,
"author": "Steve-ACET",
"author_id": 66113,
"author_profile": "https://wordpress.stackexchange.com/users/66113",
"pm_score": 2,
"selected": true,
"text": "<p>It turns out I just needed to return the $title variable which already had what I needed:</p>\n\n<pre><code>function woocommerce_endpoint_titles( $title ) {\n $sep = ' | ';\n $sitetitle = get_bloginfo();\n\n if ( is_wc_endpoint_url( 'view-order' ) ) {\n $title = 'View Order: ' . $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-account' ) ) {\n $title = 'Edit Account'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-address' ) ) {\n $title = 'Edit Address'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'lost-password' ) ) {\n $title = 'Lost Password'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'customer-logout' ) ) {\n $title = 'Logout'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-pay' ) ) {\n $title = 'Order Payment'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-received' ) ) {\n $title = 'Order Received'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'add-payment-method' ) ) {\n $title = 'Add Payment Method'. $sep . $sitetitle; \n }\n return $title;\n}\nadd_filter( 'wpseo_title','woocommerce_endpoint_titles');\n</code></pre>\n"
},
{
"answer_id": 336585,
"author": "rosie",
"author_id": 164849,
"author_profile": "https://wordpress.stackexchange.com/users/164849",
"pm_score": 2,
"selected": false,
"text": "<p>If you added custom WC endpoints on init, you can use something like this instead to check for endpoints (adjust accordingly if you're using Yoast):</p>\n\n<pre><code>function add_custom_endpoints_to_title( $post_title ) {\n\n if ( ! is_account_page() ) {\n return $post_title;\n }\n\n global $wp;\n\n if ( isset( $wp->query_vars['custom_endpoint_1'] ) ) {\n $post_title = 'Custom Endpoint 1';\n } elseif ( isset( $wp->query_vars['custom_endpoint_2'] ) ) {\n $post_title = 'Custom Endpoint 2';\n }\n\n return $post_title;\n}\n\nadd_filter( 'single_post_title', 'add_custom_endpoints_to_title', 99 );\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193695",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40679/"
] |
I use the add\_menu\_page function in my custom theme builds but when I export my local copy of the site and import it in the production site some of post id numbers change and I have to update this function manually (ie: in the code below: ***?post=8, ?post=8, ?post=10***). Is there a way to have these numbers be dynamic?
```
function custom_admin_menu_links() {
$user = wp_get_current_user();
if ( ! $user->has_cap( 'manage_options' ) ) {
add_menu_page( 'Home', 'Home', 'edit_posts', 'post.php?post=6&action=edit', '', 'dashicons-admin-home', 1);
add_menu_page( 'About', 'About', 'edit_posts', 'post.php?post=8&action=edit', '', 'dashicons-id', 2);
add_menu_page( 'Contact', 'Contact', 'edit_posts', 'post.php?post=10&action=edit', '', 'dashicons-phone', 3);
}
}
add_action( 'admin_menu', 'custom_admin_menu_links' );
```
|
It turns out I just needed to return the $title variable which already had what I needed:
```
function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order: ' . $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
}
return $title;
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
```
|
193,696 |
<p>First off, this has nothing to do with permissions, I already checked that. So please don't mark this as a duplicate.</p>
<p>Any time I try to update a plugin, I get this dialog:</p>
<p><img src="https://i.stack.imgur.com/ZDa03.png" alt="enter image description here"></p>
<p>I went overboard and allowed all permissions (-rw-rw-rw-) on all files, and <em>still</em> the plugins won't update without FTP. And SFTP is not an option, as I'm using ssh keys on this server (no passwords allowed). I'm running WP on nginx and php5-fpm. What else should I try to do?</p>
|
[
{
"answer_id": 193655,
"author": "Steve-ACET",
"author_id": 66113,
"author_profile": "https://wordpress.stackexchange.com/users/66113",
"pm_score": 2,
"selected": true,
"text": "<p>It turns out I just needed to return the $title variable which already had what I needed:</p>\n\n<pre><code>function woocommerce_endpoint_titles( $title ) {\n $sep = ' | ';\n $sitetitle = get_bloginfo();\n\n if ( is_wc_endpoint_url( 'view-order' ) ) {\n $title = 'View Order: ' . $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-account' ) ) {\n $title = 'Edit Account'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-address' ) ) {\n $title = 'Edit Address'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'lost-password' ) ) {\n $title = 'Lost Password'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'customer-logout' ) ) {\n $title = 'Logout'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-pay' ) ) {\n $title = 'Order Payment'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-received' ) ) {\n $title = 'Order Received'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'add-payment-method' ) ) {\n $title = 'Add Payment Method'. $sep . $sitetitle; \n }\n return $title;\n}\nadd_filter( 'wpseo_title','woocommerce_endpoint_titles');\n</code></pre>\n"
},
{
"answer_id": 336585,
"author": "rosie",
"author_id": 164849,
"author_profile": "https://wordpress.stackexchange.com/users/164849",
"pm_score": 2,
"selected": false,
"text": "<p>If you added custom WC endpoints on init, you can use something like this instead to check for endpoints (adjust accordingly if you're using Yoast):</p>\n\n<pre><code>function add_custom_endpoints_to_title( $post_title ) {\n\n if ( ! is_account_page() ) {\n return $post_title;\n }\n\n global $wp;\n\n if ( isset( $wp->query_vars['custom_endpoint_1'] ) ) {\n $post_title = 'Custom Endpoint 1';\n } elseif ( isset( $wp->query_vars['custom_endpoint_2'] ) ) {\n $post_title = 'Custom Endpoint 2';\n }\n\n return $post_title;\n}\n\nadd_filter( 'single_post_title', 'add_custom_endpoints_to_title', 99 );\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32201/"
] |
First off, this has nothing to do with permissions, I already checked that. So please don't mark this as a duplicate.
Any time I try to update a plugin, I get this dialog:

I went overboard and allowed all permissions (-rw-rw-rw-) on all files, and *still* the plugins won't update without FTP. And SFTP is not an option, as I'm using ssh keys on this server (no passwords allowed). I'm running WP on nginx and php5-fpm. What else should I try to do?
|
It turns out I just needed to return the $title variable which already had what I needed:
```
function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order: ' . $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
}
return $title;
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
```
|
193,707 |
<p>I'm trying to generate a table for a custom post type events, in which I have a few custom fields, one of these is the date. I want to display the posts in the table and order them by the Date value. This is my code:</p>
<p><strong>Date format</strong>: 07/07/2015 (DAY/MONTH/YEAR)</p>
<p>Right now, the loop isn't working and I don't know how to order by the date.</p>
<pre><code><div class="container">
<div class="row">
<table>
<tr>
<th>Artista</th>
<th>Fecha</th>
<th>Ciudad</th>
<th>Información</th>
</tr>
<?php $i = 0;?>
<?php while ( have_posts() ) : the_post(); ?>
<?php if($i == 0){ echo "<tr>"; }?>
<td><?php the_title(); ?></td>
<td><?php the_field('fecha_del_evento'); ?></td>
<td><?php the_field('lugar_del_evento'); ?></td>
<td><?php the_content(); ?></td>
<?php $i++;?>
<?php if($i == 4){ echo "</tr>"; $i=0;}?>
<?php endwhile; ?>
<?php if($i < 4) echo '</tr>'; ?>
</table>
<?php else: ?>
<div class="page-header"><h1>Uh Oh!</h1></div>
<p>Sorry, for some reason the contents of this page isn't displaying.</p>
<?php endif; ?>
</div><!-- END OF ROW -->
</div><!-- END OF CONTAINER -->
</code></pre>
|
[
{
"answer_id": 193655,
"author": "Steve-ACET",
"author_id": 66113,
"author_profile": "https://wordpress.stackexchange.com/users/66113",
"pm_score": 2,
"selected": true,
"text": "<p>It turns out I just needed to return the $title variable which already had what I needed:</p>\n\n<pre><code>function woocommerce_endpoint_titles( $title ) {\n $sep = ' | ';\n $sitetitle = get_bloginfo();\n\n if ( is_wc_endpoint_url( 'view-order' ) ) {\n $title = 'View Order: ' . $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-account' ) ) {\n $title = 'Edit Account'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-address' ) ) {\n $title = 'Edit Address'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'lost-password' ) ) {\n $title = 'Lost Password'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'customer-logout' ) ) {\n $title = 'Logout'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-pay' ) ) {\n $title = 'Order Payment'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-received' ) ) {\n $title = 'Order Received'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'add-payment-method' ) ) {\n $title = 'Add Payment Method'. $sep . $sitetitle; \n }\n return $title;\n}\nadd_filter( 'wpseo_title','woocommerce_endpoint_titles');\n</code></pre>\n"
},
{
"answer_id": 336585,
"author": "rosie",
"author_id": 164849,
"author_profile": "https://wordpress.stackexchange.com/users/164849",
"pm_score": 2,
"selected": false,
"text": "<p>If you added custom WC endpoints on init, you can use something like this instead to check for endpoints (adjust accordingly if you're using Yoast):</p>\n\n<pre><code>function add_custom_endpoints_to_title( $post_title ) {\n\n if ( ! is_account_page() ) {\n return $post_title;\n }\n\n global $wp;\n\n if ( isset( $wp->query_vars['custom_endpoint_1'] ) ) {\n $post_title = 'Custom Endpoint 1';\n } elseif ( isset( $wp->query_vars['custom_endpoint_2'] ) ) {\n $post_title = 'Custom Endpoint 2';\n }\n\n return $post_title;\n}\n\nadd_filter( 'single_post_title', 'add_custom_endpoints_to_title', 99 );\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60103/"
] |
I'm trying to generate a table for a custom post type events, in which I have a few custom fields, one of these is the date. I want to display the posts in the table and order them by the Date value. This is my code:
**Date format**: 07/07/2015 (DAY/MONTH/YEAR)
Right now, the loop isn't working and I don't know how to order by the date.
```
<div class="container">
<div class="row">
<table>
<tr>
<th>Artista</th>
<th>Fecha</th>
<th>Ciudad</th>
<th>Información</th>
</tr>
<?php $i = 0;?>
<?php while ( have_posts() ) : the_post(); ?>
<?php if($i == 0){ echo "<tr>"; }?>
<td><?php the_title(); ?></td>
<td><?php the_field('fecha_del_evento'); ?></td>
<td><?php the_field('lugar_del_evento'); ?></td>
<td><?php the_content(); ?></td>
<?php $i++;?>
<?php if($i == 4){ echo "</tr>"; $i=0;}?>
<?php endwhile; ?>
<?php if($i < 4) echo '</tr>'; ?>
</table>
<?php else: ?>
<div class="page-header"><h1>Uh Oh!</h1></div>
<p>Sorry, for some reason the contents of this page isn't displaying.</p>
<?php endif; ?>
</div><!-- END OF ROW -->
</div><!-- END OF CONTAINER -->
```
|
It turns out I just needed to return the $title variable which already had what I needed:
```
function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order: ' . $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
}
return $title;
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
```
|
193,709 |
<pre><code>wp_register_script('moment', plugin_dir_url( __FILE__ )."js/moment.min.js", false, null, true);
wp_register_script('fullcalendar', plugin_dir_url( __FILE__ )."js/fullcalendar.min.js", false, null, true);
wp_enqueue_script('moment');
wp_enqueue_script('fullcalendar');
wp_register_style('fullcalendarcss', 'http://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.3/fullcalendar.min.css');
wp_register_style('fullcalendarprintcss', 'http://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.3/fullcalendar.print.css');
wp_enqueue_style( 'fullcalendarcss');
wp_enqueue_style( 'fullcalendarprintcss');
</code></pre>
<p>These files which i have registered in my plugin.this is my plugin page code .</p>
<pre><code>jQuery(document).ready(function($) {
var calendar = jQuery('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
}
});
});
</code></pre>
<p>Now i am not getting any error nor getting my calendar at my page.</p>
|
[
{
"answer_id": 193655,
"author": "Steve-ACET",
"author_id": 66113,
"author_profile": "https://wordpress.stackexchange.com/users/66113",
"pm_score": 2,
"selected": true,
"text": "<p>It turns out I just needed to return the $title variable which already had what I needed:</p>\n\n<pre><code>function woocommerce_endpoint_titles( $title ) {\n $sep = ' | ';\n $sitetitle = get_bloginfo();\n\n if ( is_wc_endpoint_url( 'view-order' ) ) {\n $title = 'View Order: ' . $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-account' ) ) {\n $title = 'Edit Account'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-address' ) ) {\n $title = 'Edit Address'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'lost-password' ) ) {\n $title = 'Lost Password'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'customer-logout' ) ) {\n $title = 'Logout'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-pay' ) ) {\n $title = 'Order Payment'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-received' ) ) {\n $title = 'Order Received'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'add-payment-method' ) ) {\n $title = 'Add Payment Method'. $sep . $sitetitle; \n }\n return $title;\n}\nadd_filter( 'wpseo_title','woocommerce_endpoint_titles');\n</code></pre>\n"
},
{
"answer_id": 336585,
"author": "rosie",
"author_id": 164849,
"author_profile": "https://wordpress.stackexchange.com/users/164849",
"pm_score": 2,
"selected": false,
"text": "<p>If you added custom WC endpoints on init, you can use something like this instead to check for endpoints (adjust accordingly if you're using Yoast):</p>\n\n<pre><code>function add_custom_endpoints_to_title( $post_title ) {\n\n if ( ! is_account_page() ) {\n return $post_title;\n }\n\n global $wp;\n\n if ( isset( $wp->query_vars['custom_endpoint_1'] ) ) {\n $post_title = 'Custom Endpoint 1';\n } elseif ( isset( $wp->query_vars['custom_endpoint_2'] ) ) {\n $post_title = 'Custom Endpoint 2';\n }\n\n return $post_title;\n}\n\nadd_filter( 'single_post_title', 'add_custom_endpoints_to_title', 99 );\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75764/"
] |
```
wp_register_script('moment', plugin_dir_url( __FILE__ )."js/moment.min.js", false, null, true);
wp_register_script('fullcalendar', plugin_dir_url( __FILE__ )."js/fullcalendar.min.js", false, null, true);
wp_enqueue_script('moment');
wp_enqueue_script('fullcalendar');
wp_register_style('fullcalendarcss', 'http://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.3/fullcalendar.min.css');
wp_register_style('fullcalendarprintcss', 'http://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.3/fullcalendar.print.css');
wp_enqueue_style( 'fullcalendarcss');
wp_enqueue_style( 'fullcalendarprintcss');
```
These files which i have registered in my plugin.this is my plugin page code .
```
jQuery(document).ready(function($) {
var calendar = jQuery('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
}
});
});
```
Now i am not getting any error nor getting my calendar at my page.
|
It turns out I just needed to return the $title variable which already had what I needed:
```
function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order: ' . $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
}
return $title;
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
```
|
193,719 |
<p>For some reason, <a href="http://tedxkarachi.pk/" rel="nofollow">my client's website</a> is blank. After some debugging, I realized that all of the colors have been changed to #FFF. What would be the best way to recover the site?</p>
<p>Method #1
I install the theme again.</p>
<p>Method #2
I upload the css file again</p>
<p>Please guide me.</p>
|
[
{
"answer_id": 193655,
"author": "Steve-ACET",
"author_id": 66113,
"author_profile": "https://wordpress.stackexchange.com/users/66113",
"pm_score": 2,
"selected": true,
"text": "<p>It turns out I just needed to return the $title variable which already had what I needed:</p>\n\n<pre><code>function woocommerce_endpoint_titles( $title ) {\n $sep = ' | ';\n $sitetitle = get_bloginfo();\n\n if ( is_wc_endpoint_url( 'view-order' ) ) {\n $title = 'View Order: ' . $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-account' ) ) {\n $title = 'Edit Account'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'edit-address' ) ) {\n $title = 'Edit Address'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'lost-password' ) ) {\n $title = 'Lost Password'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'customer-logout' ) ) {\n $title = 'Logout'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-pay' ) ) {\n $title = 'Order Payment'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'order-received' ) ) {\n $title = 'Order Received'. $sep . $sitetitle; \n }\n if ( is_wc_endpoint_url( 'add-payment-method' ) ) {\n $title = 'Add Payment Method'. $sep . $sitetitle; \n }\n return $title;\n}\nadd_filter( 'wpseo_title','woocommerce_endpoint_titles');\n</code></pre>\n"
},
{
"answer_id": 336585,
"author": "rosie",
"author_id": 164849,
"author_profile": "https://wordpress.stackexchange.com/users/164849",
"pm_score": 2,
"selected": false,
"text": "<p>If you added custom WC endpoints on init, you can use something like this instead to check for endpoints (adjust accordingly if you're using Yoast):</p>\n\n<pre><code>function add_custom_endpoints_to_title( $post_title ) {\n\n if ( ! is_account_page() ) {\n return $post_title;\n }\n\n global $wp;\n\n if ( isset( $wp->query_vars['custom_endpoint_1'] ) ) {\n $post_title = 'Custom Endpoint 1';\n } elseif ( isset( $wp->query_vars['custom_endpoint_2'] ) ) {\n $post_title = 'Custom Endpoint 2';\n }\n\n return $post_title;\n}\n\nadd_filter( 'single_post_title', 'add_custom_endpoints_to_title', 99 );\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193719",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
For some reason, [my client's website](http://tedxkarachi.pk/) is blank. After some debugging, I realized that all of the colors have been changed to #FFF. What would be the best way to recover the site?
Method #1
I install the theme again.
Method #2
I upload the css file again
Please guide me.
|
It turns out I just needed to return the $title variable which already had what I needed:
```
function woocommerce_endpoint_titles( $title ) {
$sep = ' | ';
$sitetitle = get_bloginfo();
if ( is_wc_endpoint_url( 'view-order' ) ) {
$title = 'View Order: ' . $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-account' ) ) {
$title = 'Edit Account'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'edit-address' ) ) {
$title = 'Edit Address'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'lost-password' ) ) {
$title = 'Lost Password'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'customer-logout' ) ) {
$title = 'Logout'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-pay' ) ) {
$title = 'Order Payment'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'order-received' ) ) {
$title = 'Order Received'. $sep . $sitetitle;
}
if ( is_wc_endpoint_url( 'add-payment-method' ) ) {
$title = 'Add Payment Method'. $sep . $sitetitle;
}
return $title;
}
add_filter( 'wpseo_title','woocommerce_endpoint_titles');
```
|
193,721 |
<p>I'm trying to hidden or remove the price on each variable products inside dropdown menu on a single product page. Please see image attached below.</p>
<p><a href="https://imgur.com/IlNkEyZ" rel="nofollow noreferrer"><img src="https://i.imgur.com/IlNkEyZ.png" title="source: imgur.com" /></a></p>
<p>I believe here is the codes that needs to be edited. Any help is appreciated. Thanks in advance.</p>
<pre><code><?php do_action( 'woocommerce_before_add_to_cart_form' ); ?>
<div class="cart-form-wrapper clearfix">
<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo $post->ID; ?>" data-product_variations="<?php echo esc_attr( json_encode( $available_variations ) ) ?>">
<?php if ( ! empty( $available_variations ) ) : ?>
<table class="variations" cellspacing="0">
<tbody>
<?php $loop = 0; foreach ( $attributes as $name => $options ) : $loop++; ?>
<tr>
<td class="label"><label for="<?php echo sanitize_title($name); ?>"><?php echo wc_attribute_label( $name ); ?></label></td>
<td class="value"><select id="<?php echo esc_attr( sanitize_title( $name ) ); ?>" name="attribute_<?php echo sanitize_title( $name ); ?>">
<option value=""><?php echo __( 'Choose an option', 'woocommerce' ) ?>&hellip;</option>
<?php
if ( is_array( $options ) ) {
if ( isset( $_REQUEST[ 'attribute_' . sanitize_title( $name ) ] ) ) {
$selected_value = $_REQUEST[ 'attribute_' . sanitize_title( $name ) ];
} elseif ( isset( $selected_attributes[ sanitize_title( $name ) ] ) ) {
$selected_value = $selected_attributes[ sanitize_title( $name ) ];
} else {
$selected_value = '';
}
// Get terms if this is a taxonomy - ordered
if ( taxonomy_exists( $name ) ) {
$terms = wc_get_product_terms( $post->ID, $name, array( 'fields' => 'all' ) );
foreach ( $terms as $term ) {
if ( ! in_array( $term->slug, $options ) ) {
continue;
}
echo '<option value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';
}
} else {
foreach ( $options as $option ) {
echo '<option value="' . esc_attr( sanitize_title( $option ) ) . '" ' . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';
}
}
}
?>
</select> <?php
/*if ( sizeof($attributes) == $loop )
echo '<a class="reset_variations" href="#reset">' . __( 'Clear selection', 'woocommerce' ) . '</a>';*/
?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</code></pre>
|
[
{
"answer_id": 193729,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 1,
"selected": false,
"text": "<p>By using hook</p>\n\n<pre><code>remove_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_price',10);\n</code></pre>\n\n<p>or CSS</p>\n\n<pre><code>span.price\n{\n display: none !important;\n}\n</code></pre>\n\n<p>*Tag May be different as per your theme. </p>\n\n<p>Thanks, Vee</p>\n"
},
{
"answer_id": 203775,
"author": "Calvin NGUYEN",
"author_id": 80989,
"author_profile": "https://wordpress.stackexchange.com/users/80989",
"pm_score": 0,
"selected": false,
"text": "<p>You find this code on your code (shared above):</p>\n\n<pre><code>echo '<option value=\"' . esc_attr( $term->slug ) . '\" ' . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';\n</code></pre>\n\n<p>And replace that by this code:</p>\n\n<pre><code>echo '<option value=\"' . esc_attr( $term->slug ) . '\" ' . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . '>' . $term->name . '</option>';\n</code></pre>\n\n<p>And this: You need find this code:</p>\n\n<pre><code>echo '<option value=\"' . esc_attr( sanitize_title( $option ) ) . '\" ' . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';\n</code></pre>\n\n<p>And replace that by this code:</p>\n\n<pre><code>echo '<option value=\"' . esc_attr( sanitize_title( $option ) ) . '\" ' . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . '>' . $option . '</option>';\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I'm trying to hidden or remove the price on each variable products inside dropdown menu on a single product page. Please see image attached below.
[](https://imgur.com/IlNkEyZ)
I believe here is the codes that needs to be edited. Any help is appreciated. Thanks in advance.
```
<?php do_action( 'woocommerce_before_add_to_cart_form' ); ?>
<div class="cart-form-wrapper clearfix">
<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo $post->ID; ?>" data-product_variations="<?php echo esc_attr( json_encode( $available_variations ) ) ?>">
<?php if ( ! empty( $available_variations ) ) : ?>
<table class="variations" cellspacing="0">
<tbody>
<?php $loop = 0; foreach ( $attributes as $name => $options ) : $loop++; ?>
<tr>
<td class="label"><label for="<?php echo sanitize_title($name); ?>"><?php echo wc_attribute_label( $name ); ?></label></td>
<td class="value"><select id="<?php echo esc_attr( sanitize_title( $name ) ); ?>" name="attribute_<?php echo sanitize_title( $name ); ?>">
<option value=""><?php echo __( 'Choose an option', 'woocommerce' ) ?>…</option>
<?php
if ( is_array( $options ) ) {
if ( isset( $_REQUEST[ 'attribute_' . sanitize_title( $name ) ] ) ) {
$selected_value = $_REQUEST[ 'attribute_' . sanitize_title( $name ) ];
} elseif ( isset( $selected_attributes[ sanitize_title( $name ) ] ) ) {
$selected_value = $selected_attributes[ sanitize_title( $name ) ];
} else {
$selected_value = '';
}
// Get terms if this is a taxonomy - ordered
if ( taxonomy_exists( $name ) ) {
$terms = wc_get_product_terms( $post->ID, $name, array( 'fields' => 'all' ) );
foreach ( $terms as $term ) {
if ( ! in_array( $term->slug, $options ) ) {
continue;
}
echo '<option value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';
}
} else {
foreach ( $options as $option ) {
echo '<option value="' . esc_attr( sanitize_title( $option ) ) . '" ' . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';
}
}
}
?>
</select> <?php
/*if ( sizeof($attributes) == $loop )
echo '<a class="reset_variations" href="#reset">' . __( 'Clear selection', 'woocommerce' ) . '</a>';*/
?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
```
|
By using hook
```
remove_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_price',10);
```
or CSS
```
span.price
{
display: none !important;
}
```
\*Tag May be different as per your theme.
Thanks, Vee
|
193,737 |
<p>I am attempting to display the latest x posts from all categories using a custom taxonomy called 'case-studies' in WordPress.</p>
<p>I have managed to output all the category names as heading links I have also outputted some posts from the standard posts taxonomy which are in the correct categories, but I can't get this to display anything from my 'case-studies' taxonomy. When I add <code>'post_type' => 'case-studies'</code> to <code>$post_args</code> query it does not show any results.</p>
<pre><code>if (have_posts()) :
$tax = 'case-studies';
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_terms($tax, $cat_args);
foreach($categories as $category) {
echo '<p><a href="' . get_term_link( $category, $tax ) . '" title="'
. sprintf( __( "View all posts in %s" ), $category->name ) . '" '
. '>' . $category->name.'</a></p>';
$post_args = array(
'posts_per_page' => 10,
'category_name' => $category->name
);
$posts = get_posts($post_args);
foreach($posts as $post) { ?>
<a href="<?php echo get_the_permalink(); ?>"><?php echo get_the_title(); ?></a><br/>
<?php }
echo '<p><a href="' . get_term_link( $category, $tax ) . '" title="'
. sprintf( __( "View all posts in %s" ), $category->name ) . '" '
. '>View all posts in ' . $category->name.'</a></p>';
}
endif;
</code></pre>
|
[
{
"answer_id": 193729,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 1,
"selected": false,
"text": "<p>By using hook</p>\n\n<pre><code>remove_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_price',10);\n</code></pre>\n\n<p>or CSS</p>\n\n<pre><code>span.price\n{\n display: none !important;\n}\n</code></pre>\n\n<p>*Tag May be different as per your theme. </p>\n\n<p>Thanks, Vee</p>\n"
},
{
"answer_id": 203775,
"author": "Calvin NGUYEN",
"author_id": 80989,
"author_profile": "https://wordpress.stackexchange.com/users/80989",
"pm_score": 0,
"selected": false,
"text": "<p>You find this code on your code (shared above):</p>\n\n<pre><code>echo '<option value=\"' . esc_attr( $term->slug ) . '\" ' . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';\n</code></pre>\n\n<p>And replace that by this code:</p>\n\n<pre><code>echo '<option value=\"' . esc_attr( $term->slug ) . '\" ' . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . '>' . $term->name . '</option>';\n</code></pre>\n\n<p>And this: You need find this code:</p>\n\n<pre><code>echo '<option value=\"' . esc_attr( sanitize_title( $option ) ) . '\" ' . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';\n</code></pre>\n\n<p>And replace that by this code:</p>\n\n<pre><code>echo '<option value=\"' . esc_attr( sanitize_title( $option ) ) . '\" ' . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . '>' . $option . '</option>';\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193737",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75779/"
] |
I am attempting to display the latest x posts from all categories using a custom taxonomy called 'case-studies' in WordPress.
I have managed to output all the category names as heading links I have also outputted some posts from the standard posts taxonomy which are in the correct categories, but I can't get this to display anything from my 'case-studies' taxonomy. When I add `'post_type' => 'case-studies'` to `$post_args` query it does not show any results.
```
if (have_posts()) :
$tax = 'case-studies';
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_terms($tax, $cat_args);
foreach($categories as $category) {
echo '<p><a href="' . get_term_link( $category, $tax ) . '" title="'
. sprintf( __( "View all posts in %s" ), $category->name ) . '" '
. '>' . $category->name.'</a></p>';
$post_args = array(
'posts_per_page' => 10,
'category_name' => $category->name
);
$posts = get_posts($post_args);
foreach($posts as $post) { ?>
<a href="<?php echo get_the_permalink(); ?>"><?php echo get_the_title(); ?></a><br/>
<?php }
echo '<p><a href="' . get_term_link( $category, $tax ) . '" title="'
. sprintf( __( "View all posts in %s" ), $category->name ) . '" '
. '>View all posts in ' . $category->name.'</a></p>';
}
endif;
```
|
By using hook
```
remove_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_price',10);
```
or CSS
```
span.price
{
display: none !important;
}
```
\*Tag May be different as per your theme.
Thanks, Vee
|
193,743 |
<p>I have a parent theme that creates a number of custom meta boxes that are added to the "post" and "pages" post types as well as a number of post types also created by the theme.</p>
<p>In my child theme, I have created some new custom post types, so I would like to add a function somewhere in my child theme to add these pre-existing meta boxes to the new post types defined in my child theme.</p>
<p>I have tried a number of things already but in every case, short of editing the meta box file in my parent theme, the meta box fails to be added to my custom post type.</p>
<p>I would love to learn how to do this. Can someone here teach me how I would do this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 193757,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": false,
"text": "<p>This depends on how your parent theme hooks in the meta_boxes. If the callbacks are hooked to <code>add_meta_boxes</code> and written similar to the following from the Codex:</p>\n\n<pre><code>function myplugin_add_meta_box() {\n\n $screens = array( 'post', 'page' );\n\n foreach ( $screens as $screen ) {\n\n add_meta_box(\n 'myplugin_sectionid',\n __( 'My Post Section Title', 'myplugin_textdomain' ),\n 'myplugin_meta_box_callback',\n $screen\n );\n }\n}\nadd_action( 'add_meta_boxes', 'myplugin_add_meta_box' );\n</code></pre>\n\n<p>Then you aren't going to be able to add the boxes without hacking the file. That <code>$screens = array( 'post', 'page' );</code> and the array that follows will prevent it. </p>\n\n<p>Similarly, you won't be able to add:</p>\n\n<pre><code>function adding_custom_meta_boxes( $post_type, $post ) {\n if ('abcd' == $post_type) return;\n add_meta_box( \n 'my-meta-box',\n __( 'My Meta Box' ),\n 'render_my_meta_box',\n 'post',\n 'normal',\n 'default'\n );\n}\nadd_action( 'add_meta_boxes', 'adding_custom_meta_boxes', 10, 2 );\n</code></pre>\n\n<p><code>if ('abcd' == $post_type) return;</code> will prevent it. </p>\n\n<p>However, if it is hooked in with post type specific hooks <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow\">as recommended</a>...</p>\n\n<pre><code>add_action( 'add_meta_boxes_post', 'adding_custom_meta_boxes' );\n</code></pre>\n\n<p>... then adding others should be easy:</p>\n\n<pre><code>add_action( 'add_meta_boxes_mytype', 'adding_custom_meta_boxes' );\nadd_action( 'add_meta_boxes_myothertype', 'adding_custom_meta_boxes' );\n</code></pre>\n"
},
{
"answer_id": 259446,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 0,
"selected": false,
"text": "<p>If you can find the function that the parent theme defines and hooks into <code>add_meta_boxes</code>, you can remove the action and redefine it in your child theme.</p>\n\n<pre><code>function my_child_theme_meta_box_override_cb() {\n $post_types = array( 'post', 'page', 'my_other_post_type' );\n // copy the add_meta_box function from the parent theme hook below...\n}\n\nfunction wpse_override_meta_box_action(){\n remove_action( 'add_meta_boxes', 'parent_theme_meta_box_hook_cb' );\n add_action( 'add_meta_boxes', 'my_child_theme_meta_box_override_cb' );\n}\nadd_action( 'after_setup_theme', 'wpse_override_meta_box_action' );\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63580/"
] |
I have a parent theme that creates a number of custom meta boxes that are added to the "post" and "pages" post types as well as a number of post types also created by the theme.
In my child theme, I have created some new custom post types, so I would like to add a function somewhere in my child theme to add these pre-existing meta boxes to the new post types defined in my child theme.
I have tried a number of things already but in every case, short of editing the meta box file in my parent theme, the meta box fails to be added to my custom post type.
I would love to learn how to do this. Can someone here teach me how I would do this?
Thanks
|
This depends on how your parent theme hooks in the meta\_boxes. If the callbacks are hooked to `add_meta_boxes` and written similar to the following from the Codex:
```
function myplugin_add_meta_box() {
$screens = array( 'post', 'page' );
foreach ( $screens as $screen ) {
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_meta_box_callback',
$screen
);
}
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );
```
Then you aren't going to be able to add the boxes without hacking the file. That `$screens = array( 'post', 'page' );` and the array that follows will prevent it.
Similarly, you won't be able to add:
```
function adding_custom_meta_boxes( $post_type, $post ) {
if ('abcd' == $post_type) return;
add_meta_box(
'my-meta-box',
__( 'My Meta Box' ),
'render_my_meta_box',
'post',
'normal',
'default'
);
}
add_action( 'add_meta_boxes', 'adding_custom_meta_boxes', 10, 2 );
```
`if ('abcd' == $post_type) return;` will prevent it.
However, if it is hooked in with post type specific hooks [as recommended](https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes)...
```
add_action( 'add_meta_boxes_post', 'adding_custom_meta_boxes' );
```
... then adding others should be easy:
```
add_action( 'add_meta_boxes_mytype', 'adding_custom_meta_boxes' );
add_action( 'add_meta_boxes_myothertype', 'adding_custom_meta_boxes' );
```
|
193,751 |
<p>I develop a plugin that searches for a duplicates of WooCommerce products in a very specific way. It works great in our test environment, but on the client's original setup it does not execute. It just reloads the page as if nothing happened. The most obvious difference between our setup and the original website is the amount of products. Our client has the ridiculous amount of 60,000+ products in his WooCommerce store.</p>
<p>I think the query we run is maybe limited in some way, but maybe I am completely on a wrong path. ANY help is appreciated, because I am about to get crazy.</p>
<p>Here is the code in question:</p>
<pre><code> $type = 'product';
$args=array(
'post_type' => $type,
'post_status' => 'publish',
'posts_per_page' => -1
);
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['name'] === $id) {
return $key;
}
}
return null;
}
$my_query = null;
$my_query = new WP_Query($args);
$items = array();
$duplicates = array();
$name;
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$name = the_title( '', '', FALSE );
$thumb_url = get_post_thumbnail_id();
$product_description = get_the_content();
if (strpos($thumb_url,'default.png') !== false) {
$thumb_url = null;
}
$price = get_post_meta( get_the_ID(), '_price', true);
$sale = get_post_meta( get_the_ID(), '_sale_price', true);
if ($sale < $price && !empty($sale)) {
$price = $sale;
}
if (array_key_exists($name, $items)) {
$existing_product_description = $items[$name]['product_description'];
$existing_name = $items[$name]['name'];
$existing_price = $items[$name]['price'];
$existing_image = $items[$name]['featured_image'];
if ($existing_product_description != $product_description && $existing_price == $price && $existing_name == $name) {
if ($existing_image == null) {
$items[$name]['featured_image'] = $thumb_url;
}
$duplicate_id = get_the_id();
array_push($duplicates, $duplicate_id);
}
if ($existing_product_description != $product_description && $existing_price != $price && $existing_name == $name) {
if ($existing_image == null) {
$items[$name]['featured_image'] = $thumb_url;
}
}
if ($existing_product_description == $product_description && $existing_price != $price && $existing_name == $name) {
if ($existing_price > $price) {
$items[$name]['price'] = $price;
}
if ($existing_image == null) {
$items[$name]['featured_image'] = $thumb_url;
}
$duplicate_id = get_the_id();
array_push($duplicates, $duplicate_id);
}
if ($existing_product_description == $product_description && $existing_price == $price && $existing_name == $name) {
$duplicate_id = get_the_id();
array_push($duplicates, $duplicate_id);
}
}
else {
$items[$name] = array(
'id' => get_the_ID(),
'name' => $name,
'price' => $price,
'featured_image' => $thumb_url,
'product_description' => $product_description
);
}
?>
<?php
endwhile;
}
wp_reset_query(); // Restore global post data stomped by the_post().
foreach ($items as $product => $products) {
$product_id = $items[$product]['id'];
$product_new_price = $items[$product]['price'];
$product_new_thumb = $items[$product]['featured_image'];
$product_to_edit = new WC_Product($product_id);
$price = $product_to_edit->price;
set_post_thumbnail( $product_id, $product_new_thumb );
update_post_meta($product_id, '_price', $product_new_price);
update_post_meta($product_id, '_regular_price', $product_new_price);
update_post_meta( $product_id, '_sale_price', '' );
}
foreach ($duplicates as $index => $ids) {
wp_trash_post($ids);
}
</code></pre>
|
[
{
"answer_id": 193753,
"author": "Hari Om Gupta",
"author_id": 68792,
"author_profile": "https://wordpress.stackexchange.com/users/68792",
"pm_score": 0,
"selected": false,
"text": "<p>Yeah I think it works with limited no of items, I have also find similar issue with <strong>wp_query</strong>, on my client's site, there are 20,000+ products were there, btw I did resolve this by executing sql query,instead of wp_query. ;)</p>\n"
},
{
"answer_id": 193759,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I think the query we run is maybe limited in some way...</p>\n</blockquote>\n\n<p>So far as I know, your query and the processing you do of the results is going to be limited by server resources-- memory, etc-- not by WordPress other than the <a href=\"https://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP\" rel=\"nofollow noreferrer\">WordPress defined PHP memory limit</a>, to some extent. You can try altering that and see if it helps. Otherwise, you will need help from your host and you will need to post error logs and <a href=\"https://wordpress.stackexchange.com/a/95983/21376\">other debugging information</a>.</p>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57654/"
] |
I develop a plugin that searches for a duplicates of WooCommerce products in a very specific way. It works great in our test environment, but on the client's original setup it does not execute. It just reloads the page as if nothing happened. The most obvious difference between our setup and the original website is the amount of products. Our client has the ridiculous amount of 60,000+ products in his WooCommerce store.
I think the query we run is maybe limited in some way, but maybe I am completely on a wrong path. ANY help is appreciated, because I am about to get crazy.
Here is the code in question:
```
$type = 'product';
$args=array(
'post_type' => $type,
'post_status' => 'publish',
'posts_per_page' => -1
);
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['name'] === $id) {
return $key;
}
}
return null;
}
$my_query = null;
$my_query = new WP_Query($args);
$items = array();
$duplicates = array();
$name;
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$name = the_title( '', '', FALSE );
$thumb_url = get_post_thumbnail_id();
$product_description = get_the_content();
if (strpos($thumb_url,'default.png') !== false) {
$thumb_url = null;
}
$price = get_post_meta( get_the_ID(), '_price', true);
$sale = get_post_meta( get_the_ID(), '_sale_price', true);
if ($sale < $price && !empty($sale)) {
$price = $sale;
}
if (array_key_exists($name, $items)) {
$existing_product_description = $items[$name]['product_description'];
$existing_name = $items[$name]['name'];
$existing_price = $items[$name]['price'];
$existing_image = $items[$name]['featured_image'];
if ($existing_product_description != $product_description && $existing_price == $price && $existing_name == $name) {
if ($existing_image == null) {
$items[$name]['featured_image'] = $thumb_url;
}
$duplicate_id = get_the_id();
array_push($duplicates, $duplicate_id);
}
if ($existing_product_description != $product_description && $existing_price != $price && $existing_name == $name) {
if ($existing_image == null) {
$items[$name]['featured_image'] = $thumb_url;
}
}
if ($existing_product_description == $product_description && $existing_price != $price && $existing_name == $name) {
if ($existing_price > $price) {
$items[$name]['price'] = $price;
}
if ($existing_image == null) {
$items[$name]['featured_image'] = $thumb_url;
}
$duplicate_id = get_the_id();
array_push($duplicates, $duplicate_id);
}
if ($existing_product_description == $product_description && $existing_price == $price && $existing_name == $name) {
$duplicate_id = get_the_id();
array_push($duplicates, $duplicate_id);
}
}
else {
$items[$name] = array(
'id' => get_the_ID(),
'name' => $name,
'price' => $price,
'featured_image' => $thumb_url,
'product_description' => $product_description
);
}
?>
<?php
endwhile;
}
wp_reset_query(); // Restore global post data stomped by the_post().
foreach ($items as $product => $products) {
$product_id = $items[$product]['id'];
$product_new_price = $items[$product]['price'];
$product_new_thumb = $items[$product]['featured_image'];
$product_to_edit = new WC_Product($product_id);
$price = $product_to_edit->price;
set_post_thumbnail( $product_id, $product_new_thumb );
update_post_meta($product_id, '_price', $product_new_price);
update_post_meta($product_id, '_regular_price', $product_new_price);
update_post_meta( $product_id, '_sale_price', '' );
}
foreach ($duplicates as $index => $ids) {
wp_trash_post($ids);
}
```
|
>
> I think the query we run is maybe limited in some way...
>
>
>
So far as I know, your query and the processing you do of the results is going to be limited by server resources-- memory, etc-- not by WordPress other than the [WordPress defined PHP memory limit](https://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP), to some extent. You can try altering that and see if it helps. Otherwise, you will need help from your host and you will need to post error logs and [other debugging information](https://wordpress.stackexchange.com/a/95983/21376).
|
193,755 |
<p>In WordPress 4.2 it included a nice feature which labeled what page was the Front-Page and which page was the Blog ( Latest Posts ). Unfortunately, it also removes the default editor on the page assigned to show the latest posts and instead shows this message:</p>
<blockquote>
<p>You are currently editing the page that shows your latest posts.</p>
</blockquote>
<p>I want to assign content to the blog page to show above my latests posts via:</p>
<pre><code>get_post_field( 'post_content', get_option( 'page_for_posts' ) );
</code></pre>
<p>How can I re-add the default WP Editor to the Blog Page in the administration panel without adding a separate metabox?</p>
|
[
{
"answer_id": 193756,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 5,
"selected": true,
"text": "<p>In WordPress 4.2 the editor was removed on whichever page was assigned to show Latest Posts for whatever reason. The following function below\n( <a href=\"https://wordpress.org/support/topic/you-are-currently-editing-the-page-that-shows-your-latest-posts\" rel=\"noreferrer\">original solution found here</a> by <a href=\"https://wordpress.org/support/profile/crgeary\" rel=\"noreferrer\">crgeary</a> ) will re-add the editor and remove the notification:</p>\n\n<blockquote>\n <p>You are currently editing the page that shows your latest posts.</p>\n</blockquote>\n\n<p>Here's some information on the hooks used:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/edit_form_after_title/\" rel=\"noreferrer\"><code>edit_form_after_title</code></a> - Used to remove the above admin notice.</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/add_post_type_support/\" rel=\"noreferrer\"><code>add_post_type_support</code></a> - Used to give editor support back to the Latest Posts page.</li>\n</ul>\n\n<p><br /></p>\n\n<pre><code>if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {\n\n /**\n * Add the wp-editor back into WordPress after it was removed in 4.2.2.\n *\n * @param Object $post\n * @return void\n */\n function fix_no_editor_on_posts_page( $post ) {\n if( isset( $post ) && $post->ID != get_option('page_for_posts') ) {\n return;\n }\n\n remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );\n add_post_type_support( 'page', 'editor' );\n }\n add_action( 'edit_form_after_title', 'fix_no_editor_on_posts_page', 0 );\n }\n</code></pre>\n\n<h2>Edit for WordPress 4.9</h2>\n\n<p>As of WordPress 4.9.6 this fails to re-instate the editor. It looks as though the action <code>edit_form_after_title</code> isn't called soon enough. This modification, called on the earliest non-deprecated hook following the editor's removal in <code>edit-form-advanced.php</code>, seems to work OK.</p>\n\n<p>Apart from the change of hook, there's a change to the number of parameters too.</p>\n\n<pre><code>if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {\n\n function fix_no_editor_on_posts_page( $post_type, $post ) {\n if( isset( $post ) && $post->ID != get_option('page_for_posts') ) {\n return;\n }\n\n remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );\n add_post_type_support( 'page', 'editor' );\n }\n\n add_action( 'add_meta_boxes', 'fix_no_editor_on_posts_page', 0, 2 );\n\n }\n</code></pre>\n"
},
{
"answer_id": 350563,
"author": "Wojtek Szałkiewicz",
"author_id": 176837,
"author_profile": "https://wordpress.stackexchange.com/users/176837",
"pm_score": 3,
"selected": false,
"text": "<p>It's been a while, but I came across this topic while looking for a way to enable gutenberg editor on the Blog Page. Didn't find any clue in google, so I dived into wordpress code and found the solution. Here is the code:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'replace_editor', 'enable_gutenberg_editor_for_blog_page', 10, 2 );\n/**\n * Simulate non-empty content to enable Gutenberg editor\n *\n * @param bool $replace Whether to replace the editor.\n * @param WP_Post $post Post object.\n * @return bool\n */\nfunction enable_gutenberg_editor_for_blog_page( $replace, $post ) {\n\n if ( ! $replace && absint( get_option( 'page_for_posts' ) ) === $post->ID && empty( $post->post_content ) ) {\n // This comment will be removed by Gutenberg since it won't parse into block.\n $post->post_content = '<!--non-empty-content-->';\n }\n\n return $replace;\n\n}\n</code></pre>\n\n<p>I used 'replace_editor' filter just because it is the last filter/action used before the check if Gutenberg should load. This could be any earlier filter or action with current post object available.</p>\n\n<p>WordPress checks for two things: if the current post ID is the same as <code>page_for_posts</code> option and if the content is empty, so in this filter we just add some fake content which will be removed by Gutenberg since it is random HTML comment.</p>\n\n<p>Hope someone will find it useful :)</p>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193755",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7355/"
] |
In WordPress 4.2 it included a nice feature which labeled what page was the Front-Page and which page was the Blog ( Latest Posts ). Unfortunately, it also removes the default editor on the page assigned to show the latest posts and instead shows this message:
>
> You are currently editing the page that shows your latest posts.
>
>
>
I want to assign content to the blog page to show above my latests posts via:
```
get_post_field( 'post_content', get_option( 'page_for_posts' ) );
```
How can I re-add the default WP Editor to the Blog Page in the administration panel without adding a separate metabox?
|
In WordPress 4.2 the editor was removed on whichever page was assigned to show Latest Posts for whatever reason. The following function below
( [original solution found here](https://wordpress.org/support/topic/you-are-currently-editing-the-page-that-shows-your-latest-posts) by [crgeary](https://wordpress.org/support/profile/crgeary) ) will re-add the editor and remove the notification:
>
> You are currently editing the page that shows your latest posts.
>
>
>
Here's some information on the hooks used:
* [`edit_form_after_title`](https://developer.wordpress.org/reference/hooks/edit_form_after_title/) - Used to remove the above admin notice.
* [`add_post_type_support`](https://developer.wordpress.org/reference/functions/add_post_type_support/) - Used to give editor support back to the Latest Posts page.
```
if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {
/**
* Add the wp-editor back into WordPress after it was removed in 4.2.2.
*
* @param Object $post
* @return void
*/
function fix_no_editor_on_posts_page( $post ) {
if( isset( $post ) && $post->ID != get_option('page_for_posts') ) {
return;
}
remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );
add_post_type_support( 'page', 'editor' );
}
add_action( 'edit_form_after_title', 'fix_no_editor_on_posts_page', 0 );
}
```
Edit for WordPress 4.9
----------------------
As of WordPress 4.9.6 this fails to re-instate the editor. It looks as though the action `edit_form_after_title` isn't called soon enough. This modification, called on the earliest non-deprecated hook following the editor's removal in `edit-form-advanced.php`, seems to work OK.
Apart from the change of hook, there's a change to the number of parameters too.
```
if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {
function fix_no_editor_on_posts_page( $post_type, $post ) {
if( isset( $post ) && $post->ID != get_option('page_for_posts') ) {
return;
}
remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );
add_post_type_support( 'page', 'editor' );
}
add_action( 'add_meta_boxes', 'fix_no_editor_on_posts_page', 0, 2 );
}
```
|
193,766 |
<p>The challenge is the following:
How to set the output price converted in local currency in frontend site shop? We need to have base price in USD in admin area, but on the site shop we need to use local currency without possibility to select any other currencies, just strictly show prices converted in local currency.</p>
<p>I've used woocommerce currency converter plugin but it works as a widget and not on all shop areas, and I need to show prices in local currencies and without currency selector widget.</p>
<p>Thank you in advance.</p>
|
[
{
"answer_id": 194337,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": -1,
"selected": false,
"text": "<p>There are many plugin provide these kind of functionality. You need to research for the same some plugin which can help you achieve you goal are as follows:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/woocommerce-currency-switcher/\" rel=\"nofollow\">WooCommerce Currency Switcher</a>\nThis Plugin allows you to switch to different currencies and get their rates converted in the real time</li>\n<li><a href=\"https://wordpress.org/plugins/woocommerce-multilingual/\" rel=\"nofollow\">WooCommerce Multilingual - run WooCommerce with WPML</a>\nThis plugin makes it possible to run fully multilingual e-commerce sites using WooCommerce and WPML. It makes products and store pages translatable, lets visitors switch languages and order products in their language.</li>\n</ul>\n\n<p>These are some of the plugins which enables running a single WooCommerce store with multiple currencies.</p>\n"
},
{
"answer_id": 247003,
"author": "TDEgypt",
"author_id": 107500,
"author_profile": "https://wordpress.stackexchange.com/users/107500",
"pm_score": 1,
"selected": false,
"text": "<p>I've just ran into your question, and of course it was almost a year, so, I'm not sure if you've solved the issue. I'll put an answer here in case you still didn't (which I doubt), and for other people may be searching for an answer.\nMy suggestion is to go with JQuery on the Front End to replace the price and the currency symbol based on the visitor selected country or the admin's set local currency.</p>\n\n<p>In the admin set model, based on the StoreFront Theme:</p>\n\n<ul>\n<li><p>First, you enqueue a JQuery script that will make the change, this goes in you main plugin page:</p>\n\n<p>add_action( 'wp_enqueue_scripts', 'add_local_currency_changer' );<br>\nfunction add_local_currency_changer() {\n wp_enqueue_script('local_currency_changer', // name your script so that you can attach other scripts and de-register, etc.\n '/wp-content/plugins/YOUR-PLUGIN-DIR/js/local_currency_changer.js', // this is the location of your script file\n array('jquery') // this array lists the scripts upon which your script depends\n );\n}</p></li>\n<li><p>Second, you create the JQuery script which should be similar to:</p>\n\n<pre><code><script>\n jQuery(document).ready(function($) {\n $(\".woocommerce-price-amount\"). innerHTML('<span class=\"woocommerce-Price- currencySymbol\">--YOUR NEW LOCAL CURRENCY SYMBOL HERE--</span>');\n $(this).append(\"--YOUR NEW LOCAL PRICE HERE--\");\n })\n</script>\n</code></pre></li>\n</ul>\n\n<p>Please note that I didn't test the above code. Still, it is just a suggestion for the direction where you would be heading.</p>\n\n<p>Also, please note that \"--YOUR NEW LOCAL PRICE HERE--\" can be a complex calculation or even may use Ajax to call a dynamic rate service such as Google...etc, and not just a static text.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193766",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75792/"
] |
The challenge is the following:
How to set the output price converted in local currency in frontend site shop? We need to have base price in USD in admin area, but on the site shop we need to use local currency without possibility to select any other currencies, just strictly show prices converted in local currency.
I've used woocommerce currency converter plugin but it works as a widget and not on all shop areas, and I need to show prices in local currencies and without currency selector widget.
Thank you in advance.
|
I've just ran into your question, and of course it was almost a year, so, I'm not sure if you've solved the issue. I'll put an answer here in case you still didn't (which I doubt), and for other people may be searching for an answer.
My suggestion is to go with JQuery on the Front End to replace the price and the currency symbol based on the visitor selected country or the admin's set local currency.
In the admin set model, based on the StoreFront Theme:
* First, you enqueue a JQuery script that will make the change, this goes in you main plugin page:
add\_action( 'wp\_enqueue\_scripts', 'add\_local\_currency\_changer' );
function add\_local\_currency\_changer() {
wp\_enqueue\_script('local\_currency\_changer', // name your script so that you can attach other scripts and de-register, etc.
'/wp-content/plugins/YOUR-PLUGIN-DIR/js/local\_currency\_changer.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
* Second, you create the JQuery script which should be similar to:
```
<script>
jQuery(document).ready(function($) {
$(".woocommerce-price-amount"). innerHTML('<span class="woocommerce-Price- currencySymbol">--YOUR NEW LOCAL CURRENCY SYMBOL HERE--</span>');
$(this).append("--YOUR NEW LOCAL PRICE HERE--");
})
</script>
```
Please note that I didn't test the above code. Still, it is just a suggestion for the direction where you would be heading.
Also, please note that "--YOUR NEW LOCAL PRICE HERE--" can be a complex calculation or even may use Ajax to call a dynamic rate service such as Google...etc, and not just a static text.
Hope this helps.
|
193,776 |
<p>I'm using html5 support for input formats and custom comment form fields with this code:</p>
<pre><code><?php
$commenter = wp_get_current_commenter();
$args = wp_parse_args( $args );
if ( ! isset( $args['format'] ) )
$args['format'] = current_theme_supports( 'html5', 'comment-form' ) ? 'html5' : 'xhtml';
$req = get_option( 'require_name_email' );
$aria_req = ( $req ? " aria-required='true'" : '' );
$html_req = ( $req ? " required='required'" : '' );
$html5 = 'html5' === $args['format'];
comment_form(
array(
'comment_notes_after' => '',
'comment_field' => '<div class="comment-form-comment form-group"><label class="control-label" for="comment">' . __( 'Comment', 'odin' ) . '</label><div class="controls"><textarea id="comment" name="comment" cols="45" rows="8" class="form-control" aria-required="true" ></textarea></div></div>',
'fields' => apply_filters( 'comment_form_default_fields', array(
'author' => '<div class="comment-form-author form-group">' . '<label class="control-label" for="author">' . __( 'Name', 'odin' ) . ( $req ? '<span class="required"> *</span>' : '' ) . '</label><input class="form-control" id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . $html_req . ' /></div>',
'email' => '<div class="comment-form-email form-group"><label class="control-label" for="email">' . __( 'E-mail', 'odin' ) . ( $req ? '<span class="required"> *</span>' : '' ) . '</label><input class="form-control" id="email" name="email" ' . ( $html5 ? 'type="email"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . $html_req . ' /></div>',
'url' => '<div class="comment-form-url form-group"><label class="control-label" for="url">' . __( 'Website', 'odin' ) . '</label>' . '<input class="form-control" id="url" name="url" ' . ( $html5 ? 'type="url"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></div>' ) )
)
); ?>
</code></pre>
<p>Leaving everything ready for validation html5, except for the novalidade attribute of the tag.
I am currently removing with jQuery, but I wonder if there is some way via WP / PHP</p>
|
[
{
"answer_id": 203482,
"author": "pdme",
"author_id": 35726,
"author_profile": "https://wordpress.stackexchange.com/users/35726",
"pm_score": 2,
"selected": false,
"text": "<p>It seems WP core adds the novlidate attribute to the comment form when your theme has HTML5 support enabled for comment forms (see includes/comment-template.php).</p>\n\n<p>To disable it, use</p>\n\n<pre><code>remove_theme_support('html5', 'comment-form');\n</code></pre>\n"
},
{
"answer_id": 239504,
"author": "Ha Doan Ngoc",
"author_id": 77943,
"author_profile": "https://wordpress.stackexchange.com/users/77943",
"pm_score": -1,
"selected": false,
"text": "<p>If you set format of the comment form to xhtml, the \"novalidate\" will be removed. Like this</p>\n\n<pre><code>$comments_args = array( \n 'format' => 'xhtml'\n );\n comment_form($comments_args);\n</code></pre>\n"
},
{
"answer_id": 273567,
"author": "Farhad Sakhaei",
"author_id": 114465,
"author_profile": "https://wordpress.stackexchange.com/users/114465",
"pm_score": -1,
"selected": false,
"text": "<p>Use this function rather than <code>comment_form()</code></p>\n\n<pre><code>function validate_comment_form(){\n ob_start();\n comment_form();\n echo str_replace('novalidate','data-toggle=\"validator\" ',ob_get_clean());\n}\n</code></pre>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193776",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71254/"
] |
I'm using html5 support for input formats and custom comment form fields with this code:
```
<?php
$commenter = wp_get_current_commenter();
$args = wp_parse_args( $args );
if ( ! isset( $args['format'] ) )
$args['format'] = current_theme_supports( 'html5', 'comment-form' ) ? 'html5' : 'xhtml';
$req = get_option( 'require_name_email' );
$aria_req = ( $req ? " aria-required='true'" : '' );
$html_req = ( $req ? " required='required'" : '' );
$html5 = 'html5' === $args['format'];
comment_form(
array(
'comment_notes_after' => '',
'comment_field' => '<div class="comment-form-comment form-group"><label class="control-label" for="comment">' . __( 'Comment', 'odin' ) . '</label><div class="controls"><textarea id="comment" name="comment" cols="45" rows="8" class="form-control" aria-required="true" ></textarea></div></div>',
'fields' => apply_filters( 'comment_form_default_fields', array(
'author' => '<div class="comment-form-author form-group">' . '<label class="control-label" for="author">' . __( 'Name', 'odin' ) . ( $req ? '<span class="required"> *</span>' : '' ) . '</label><input class="form-control" id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . $html_req . ' /></div>',
'email' => '<div class="comment-form-email form-group"><label class="control-label" for="email">' . __( 'E-mail', 'odin' ) . ( $req ? '<span class="required"> *</span>' : '' ) . '</label><input class="form-control" id="email" name="email" ' . ( $html5 ? 'type="email"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . $html_req . ' /></div>',
'url' => '<div class="comment-form-url form-group"><label class="control-label" for="url">' . __( 'Website', 'odin' ) . '</label>' . '<input class="form-control" id="url" name="url" ' . ( $html5 ? 'type="url"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></div>' ) )
)
); ?>
```
Leaving everything ready for validation html5, except for the novalidade attribute of the tag.
I am currently removing with jQuery, but I wonder if there is some way via WP / PHP
|
It seems WP core adds the novlidate attribute to the comment form when your theme has HTML5 support enabled for comment forms (see includes/comment-template.php).
To disable it, use
```
remove_theme_support('html5', 'comment-form');
```
|
193,791 |
<p>I know I can use REGEXP in WP_Query like this:</p>
<pre><code>$query = new WP_Query(array(
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'custom_fields',
'value' => 'foo[(][0-9][)]', // with regex stuff
'compare' => 'REGEXP',
),
),
));
</code></pre>
<p>But I need regular expressions in the key too. Like this:</p>
<pre><code>$query = new WP_Query(array(
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'custom_fields[(][0-9][)]', // with regex stuff
'value' => 'foo',
'compare' => 'REGEXP',
),
),
));
</code></pre>
<p>Is there any way to achieve this with a filter maybe? Or do I have to build it all myself with an own SQL query?</p>
|
[
{
"answer_id": 193841,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Here's one experimental idea:</p>\n\n<p>Assume we got: </p>\n\n<blockquote>\n <p>post <strong>A</strong> with the custom field <code>location1</code> as <em>UK - London</em></p>\n \n <p>post <strong>B</strong> with the custom field <code>location2</code> as <em>France - Paris</em></p>\n \n <p>post <strong>C</strong> with the custom field <code>location3</code> as <em>USA - New York</em></p>\n</blockquote>\n\n<p>Then we could use, for example:</p>\n\n<pre><code>$args = [\n 'meta_query' => [\n 'relation' => 'OR',\n [\n 'key' => \"^location[0-9]\",\n '_key_compare' => 'REGEXP',\n 'value' => 'London',\n 'compare' => 'LIKE',\n ],\n [\n 'key' => 'location%',\n '_key_compare' => 'LIKE',\n 'value' => 'Paris',\n 'compare' => 'LIKE'\n ],\n [\n 'key' => 'location3',\n 'value' => 'New York',\n 'compare' => 'LIKE'\n ]\n ]\n];\n</code></pre>\n\n<p>where we support the custom <code>_key_compare</code> argument with the following plugin:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Extended Meta Key Search In WP_Query\n * Description: Custom '_key_compare' argument as REGEXP, RLIKE or LIKE\n * Plugin URI: http://wordpress.stackexchange.com/a/193841/26350\n * Plugin Author: Birgir Erlendsson (birgire)\n * Version: 0.0.3\n */\n\nadd_action( 'pre_get_posts', function( $q )\n{\n // Check the meta query:\n $mq = $q->get( 'meta_query' );\n\n if( empty( $mq ) )\n return;\n\n // Init:\n $marker = '___tmp_marker___'; \n $rx = [];\n\n // Collect all the sub meta queries, that use REGEXP, RLIKE or LIKE:\n foreach( $mq as $k => $m ) \n {\n if( isset( $m['_key_compare'] )\n && in_array( strtoupper( $m['_key_compare'] ), [ 'REGEXP', 'RLIKE', 'LIKE' ] )\n && isset( $m['key'] )\n ) {\n // Mark the key with a unique string to secure the later replacements:\n $m['key'] .= $marker . $k; // Make the appended tmp marker unique\n\n // Modify the corresponding original query variable:\n $q->query_vars['meta_query'][$k]['key'] = $m['key'];\n\n // Collect it:\n $rx[$k] = $m;\n }\n }\n\n // Nothing to do:\n if( empty( $rx ) )\n return;\n\n // Get access the generated SQL of the meta query:\n add_filter( 'get_meta_sql', function( $sql ) use ( $rx, $marker )\n {\n // Only run once:\n static $nr = 0; \n if( 0 != $nr++ )\n return $sql;\n\n // Modify WHERE part where we replace the temporary markers:\n foreach( $rx as $k => $r )\n {\n $sql['where'] = str_replace(\n sprintf(\n \".meta_key = '%s' \",\n $r['key']\n ),\n sprintf(\n \".meta_key %s '%s' \",\n $r['_key_compare'],\n str_replace(\n $marker . $k,\n '',\n $r['key']\n )\n ),\n $sql['where']\n );\n }\n return $sql;\n });\n\n});\n</code></pre>\n\n<p>where we add unique markers on each meta key for the string replacements.</p>\n\n<p>Note that this doesn't support regex character <em>escaping</em>, like <code>\\(</code> and <code>\\\\</code>.</p>\n"
},
{
"answer_id": 214919,
"author": "Rogelio Vargas",
"author_id": 87045,
"author_profile": "https://wordpress.stackexchange.com/users/87045",
"pm_score": 1,
"selected": false,
"text": "<p>Your answer is perfect working in the first array lvl, for example: </p>\n\n<pre><code>$args['meta_query'][] = array(\n\n 'key' => 'tour_itinerario_ciudades_repeater_%_tour_ciudades_nombre',\n '_key_compare' => 'LIKE',\n 'value' => 'MEXICO',\n 'compare' => 'LIKE',\n );\n</code></pre>\n\n<p>I need do some modifications for work in the second lvl in the array:</p>\n\n<pre><code>$args['meta_query'][] = array(\n 'relation' => 'OR',\n array(\n 'key' => 'tour_itinerario_ciudades_repeater_%_tour_ciudades_nombre',\n '_key_compare' => 'LIKE',\n 'value' => 'CONDESA',\n 'compare' => 'LIKE',\n ),\n array(\n 'key' => 'tour_itinerario_ciudades_repeater_%_tour_ciudades_nombre',\n '_key_compare' => 'LIKE',\n 'value' => 'Ciudad 1',\n 'compare' => 'LIKE',\n )\n);\n</code></pre>\n\n<p>Now, </p>\n\n<pre><code>add_action('pre_get_posts', function( $q ) {\n// Check the meta query:\n$mq = $q->get('meta_query');\n\nif (empty($mq))\n return;\n\n// Init:\n$marker = '___tmp_marker___';\n$rx = [];\n\n// Collect all the sub meta queries, that use REGEXP, RLIKE or LIKE:\n// Only works for 1st level in array\nforeach ($mq as $k => $m) {\n if (isset($m['_key_compare']) && in_array(strtoupper($m['_key_compare']), [ 'REGEXP', 'RLIKE', 'LIKE']) && isset($m['key'])\n ) {\n // Mark the key with a unique string to secure the later replacements:\n $m['key'] .= $marker . $k; // Make the appended tmp marker unique\n // Modify the corresponding original query variable:\n $q->query_vars['meta_query'][$k]['key'] = $m['key'];\n\n // Collect it:\n $rx[$k] = $m;\n }\n}\n\n// custom code to make it work with arguments on Multidimensional array \nforeach ($mq as $k => $m) {\n foreach ($m as $k_i => $m_i) {\n if (count($m_i) >= 3) {\n if (isset($m_i['_key_compare']) && in_array(strtoupper($m_i['_key_compare']), [ 'REGEXP', 'RLIKE', 'LIKE']) && isset($m_i['key'])\n ) {\n // Mark the key with a unique string to secure the later replacements:\n $m_i['key'] .= $marker . $k_i; // Make the appended tmp marker unique\n // Modify the corresponding original query variable:\n $q->query_vars['meta_query'][$k][$k_i]['key'] = $m_i['key'];\n\n // Collect it:\n $rx[$k][$k_i] = $m_i;\n }\n }\n }\n}\n\n\n// Nothing to do:\nif (empty($rx))\n return;\n\n// Get access the generated SQL of the meta query:\nadd_filter('get_meta_sql', function( $sql ) use ( $rx, $marker ) {\n // Only run once:\n static $nr = 0;\n if (0 != $nr++)\n return $sql;\n\n // Modify WHERE part where we replace the temporary markers:\n //PRIMER NIVEL\n foreach ($rx as $k => $r) {\n $sql['where'] = str_replace(\n sprintf(\n \".meta_key = '%s' \", $r['key']\n ), sprintf(\n \".meta_key %s '%s' \", $r['_key_compare'], str_replace(\n $marker . $k, '', $r['key']\n )\n ), $sql['where']\n );\n }\n //SECOND NIVEL\n foreach ($rx as $k => $r) {\n //TODO: test with several cases since may have bugs\n if (!isset($r['key'])) {//FORZO LA ENTRADA \n foreach ($r as $k_i => $r_i) {\n $sql['where'] = str_replace(\n sprintf(\n \".meta_key = '%s' \", $r_i['key']\n ), sprintf(\n \".meta_key %s '%s' \", $r_i['_key_compare'], str_replace(\n $marker . $k_i, '', $r_i['key']\n )\n ), $sql['where']\n );\n }\n }\n }\n\n var_dump($sql);\n return $sql;\n});\n</code></pre>\n\n<p>});\nJust for if any need similar answer,</p>\n\n<p>THK AGAIN</p>\n"
}
] |
2015/07/07
|
[
"https://wordpress.stackexchange.com/questions/193791",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21207/"
] |
I know I can use REGEXP in WP\_Query like this:
```
$query = new WP_Query(array(
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'custom_fields',
'value' => 'foo[(][0-9][)]', // with regex stuff
'compare' => 'REGEXP',
),
),
));
```
But I need regular expressions in the key too. Like this:
```
$query = new WP_Query(array(
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'custom_fields[(][0-9][)]', // with regex stuff
'value' => 'foo',
'compare' => 'REGEXP',
),
),
));
```
Is there any way to achieve this with a filter maybe? Or do I have to build it all myself with an own SQL query?
|
Here's one experimental idea:
Assume we got:
>
> post **A** with the custom field `location1` as *UK - London*
>
>
> post **B** with the custom field `location2` as *France - Paris*
>
>
> post **C** with the custom field `location3` as *USA - New York*
>
>
>
Then we could use, for example:
```
$args = [
'meta_query' => [
'relation' => 'OR',
[
'key' => "^location[0-9]",
'_key_compare' => 'REGEXP',
'value' => 'London',
'compare' => 'LIKE',
],
[
'key' => 'location%',
'_key_compare' => 'LIKE',
'value' => 'Paris',
'compare' => 'LIKE'
],
[
'key' => 'location3',
'value' => 'New York',
'compare' => 'LIKE'
]
]
];
```
where we support the custom `_key_compare` argument with the following plugin:
```
<?php
/**
* Plugin Name: Extended Meta Key Search In WP_Query
* Description: Custom '_key_compare' argument as REGEXP, RLIKE or LIKE
* Plugin URI: http://wordpress.stackexchange.com/a/193841/26350
* Plugin Author: Birgir Erlendsson (birgire)
* Version: 0.0.3
*/
add_action( 'pre_get_posts', function( $q )
{
// Check the meta query:
$mq = $q->get( 'meta_query' );
if( empty( $mq ) )
return;
// Init:
$marker = '___tmp_marker___';
$rx = [];
// Collect all the sub meta queries, that use REGEXP, RLIKE or LIKE:
foreach( $mq as $k => $m )
{
if( isset( $m['_key_compare'] )
&& in_array( strtoupper( $m['_key_compare'] ), [ 'REGEXP', 'RLIKE', 'LIKE' ] )
&& isset( $m['key'] )
) {
// Mark the key with a unique string to secure the later replacements:
$m['key'] .= $marker . $k; // Make the appended tmp marker unique
// Modify the corresponding original query variable:
$q->query_vars['meta_query'][$k]['key'] = $m['key'];
// Collect it:
$rx[$k] = $m;
}
}
// Nothing to do:
if( empty( $rx ) )
return;
// Get access the generated SQL of the meta query:
add_filter( 'get_meta_sql', function( $sql ) use ( $rx, $marker )
{
// Only run once:
static $nr = 0;
if( 0 != $nr++ )
return $sql;
// Modify WHERE part where we replace the temporary markers:
foreach( $rx as $k => $r )
{
$sql['where'] = str_replace(
sprintf(
".meta_key = '%s' ",
$r['key']
),
sprintf(
".meta_key %s '%s' ",
$r['_key_compare'],
str_replace(
$marker . $k,
'',
$r['key']
)
),
$sql['where']
);
}
return $sql;
});
});
```
where we add unique markers on each meta key for the string replacements.
Note that this doesn't support regex character *escaping*, like `\(` and `\\`.
|
193,825 |
<p>I have recently finished developing my latest WordPress theme for my own site and as usual I was going to use maxcdn and w3tc to make it faster!</p>
<p>However my Hosting company have started up their own cdn service and I have got 3 months free to test it out! However it is not as easy to set up as Maxcdn and have been told that I need to change the resource url to use cdn url and serve my images, css and js files.</p>
<p>I have added all my css and js files in my function.php file like so...</p>
<pre><code>wp_enqueue_style('BrumWebEngineer-style', get_stylesheet_uri());
wp_enqueue_style('BrumWebEngineer-core', get_template_directory_uri() . '/css/core.css');
</code></pre>
<p>Naturally I cannot replace the get_template_diretory_uri with the cdn url so am wondering how I can go about this.</p>
<p>Many thanks.</p>
|
[
{
"answer_id": 193834,
"author": "Phillip Dews",
"author_id": 75827,
"author_profile": "https://wordpress.stackexchange.com/users/75827",
"pm_score": 1,
"selected": false,
"text": "<p>I Finally figure it out!</p>\n\n<p>By selecting the General settings under W3TC I selected CDN and CDN Type I then selected Generic Mirror.</p>\n\n<p>I then clicked on the CDN link under performance and was able to add my CDN URL and test the mirror!\nPretty simple when you know how!</p>\n"
},
{
"answer_id": 193835,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": true,
"text": "<p>To dinamically change the stylesheet and template URI you can use <code>stylesheet_uri</code> filter and <code>template_directory_uri</code> filter.</p>\n\n<p>For example:</p>\n\n<pre><code>add_filter( 'stylesheet_uri', function( $stylesheet_uri ) {\n\n $stylesheet_uri = 'your new stylesheet URI here';\n\n return $stylesheet_uri;\n\n} );\n</code></pre>\n\n<p>But, as you are using W3TC, you can configure that change in the plugin itself (Generic Mirror and Self-hosted CDN options), even you can configure pushing files automatically if the CDN service support it.</p>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193825",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75827/"
] |
I have recently finished developing my latest WordPress theme for my own site and as usual I was going to use maxcdn and w3tc to make it faster!
However my Hosting company have started up their own cdn service and I have got 3 months free to test it out! However it is not as easy to set up as Maxcdn and have been told that I need to change the resource url to use cdn url and serve my images, css and js files.
I have added all my css and js files in my function.php file like so...
```
wp_enqueue_style('BrumWebEngineer-style', get_stylesheet_uri());
wp_enqueue_style('BrumWebEngineer-core', get_template_directory_uri() . '/css/core.css');
```
Naturally I cannot replace the get\_template\_diretory\_uri with the cdn url so am wondering how I can go about this.
Many thanks.
|
To dinamically change the stylesheet and template URI you can use `stylesheet_uri` filter and `template_directory_uri` filter.
For example:
```
add_filter( 'stylesheet_uri', function( $stylesheet_uri ) {
$stylesheet_uri = 'your new stylesheet URI here';
return $stylesheet_uri;
} );
```
But, as you are using W3TC, you can configure that change in the plugin itself (Generic Mirror and Self-hosted CDN options), even you can configure pushing files automatically if the CDN service support it.
|
193,828 |
<p>I have a piece of JS code that I use show/hide customizer control groups depending on a select item value.</p>
<p>The code was working fine until recent wp update (not sure which version first broke this). </p>
<p>Here is the code for enqueuing the js file.</p>
<pre><code>add_action('customize_controls_print_scripts', 'ppl_customize_controls_scripts');
function ppl_customize_controls_scripts(){
wp_register_script( 'ppl-customize-control', get_template_directory_uri().'/js/customizer-control.js', array('jquery'), 1, true);
wp_enqueue_script( 'ppl-customize-control' );
}
</code></pre>
<p><strong>The JS file</strong></p>
<pre><code>jQuery(document).ready(function($){
var skin_select = $('#customize-control-ppl-ninja-theme-options-skin').find('select');
//alert(skin_select.attr('class'));
var selected_val = skin_select.children('option:selected').val();
var custom_group = [
'#accordion-section-custom_header_styles',
'#accordion-section-custom_slider_styles',
'#accordion-section-custom_footer_styles',
'#accordion-section-custom_general_colors'
];
if(selected_val != 4){
hide_custom_controls(custom_group);
}
skin_select.change(function(){
var val = $(this).val();
if(val != 4){
hide_custom_controls(custom_group);
}else{
show_custom_controls(custom_group);
}
});
function hide_custom_controls(custom_group){
var selector = custom_group.join(',');
$(selector).hide();
}
function show_custom_controls(custom_group){
var selector = custom_group.join(',');
$(selector).show();
}
});
</code></pre>
<p><strong>The problem is</strong>, JS loads and hides the customizer control section just fine with inline css <code>display:none</code>. Then the cusomizer js script revises it and update the inline css to <code>display:list-item</code> which makes them visible. So, I need to run the JS code later after the customizer loads fully.</p>
<p>I looked into customizer script in wp-includes directory but haven't find anything that I can use. Perhaps I missed something.</p>
<h2>Further Information</h2>
<ol>
<li><p>The code that revising the css can be found in <a href="https://core.trac.wordpress.org/browser/trunk/src/wp-admin/js/customize-controls.js#L2584" rel="nofollow"><code>/wp-admin/js/customize-controls.js</code></a>. </p></li>
<li><p>The script is using the <code>ready</code> event to add class and revise visibility of panels, sections and controls. But I am unable to add listener to that event.</p></li>
<li><p>The property activePanels, activeSections, activeControls are set from PHP from the file <a href="https://core.trac.wordpress.org/browser/trunk/src/wp-admin/customize.php#L313" rel="nofollow"><code>/wp-admin/customize.php</code></a> I have found no way to overwrite that variable as you can see it is printed just before the body tag ends.</p></li>
</ol>
<p>So, the possible solution is perhaps finding a way to hook into the <code>ready</code> event.</p>
|
[
{
"answer_id": 195031,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like a timing problem to me, maybe/probably I'm oversimplifying this, but what about making use of the <code>$debs</code> parameter <code>wp_register_script</code> and <code>wp_enqueue_script</code> are offering to control load order, where one of those - in the order they are added at <code>script-loader.php</code> - <code>customize-base</code>, <code>customize-loader</code>, <code>customize-preview</code>, <code>customize-models</code>, <code>customize-views</code>, <code>customize-controls</code>, <code>customize-widgets</code> or <code>customize-preview-widgets</code> should be a dependency.</p>\n"
},
{
"answer_id": 195439,
"author": "Matt van Andel",
"author_id": 15324,
"author_profile": "https://wordpress.stackexchange.com/users/15324",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like a dependency problem. You're only checking for jQuery, so your script could be getting preempted. You can ensure your script loads after all the other customizer scripts with <code>'customize-preview-widgets'</code>. Try this…</p>\n\n<pre><code>add_action('customize_preview_init', 'ppl_customize_controls_scripts');\nfunction ppl_customize_controls_scripts(){\n wp_enqueue_script(\n 'ppl-customize-control',\n get_template_directory_uri().'/js/customizer-control.js',\n array( 'jquery','customize-preview-widgets' ),\n '',\n true\n );\n}\n</code></pre>\n"
},
{
"answer_id": 195548,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than trying to divine the mysteries of the customizer javascript initialization, which as you say is far from clear, you could use a <a href=\"https://developer.wordpress.org/themes/advanced-topics/customizer-api/#custom-controls-sections-and-panels\" rel=\"nofollow\">custom control</a> to inject your javascript, by overriding the <code>render_content()</code>, eg</p>\n\n<pre><code>add_action( 'customize_register', function ( $wp_customize ) {\n // Custom control.\n class PPL_Ninja_Skin_Select_Customize_Control extends WP_Customize_Control {\n public $type = 'select';\n\n // Override to inject our javascript.\n public function render_content() {\n parent::render_content();\n ?>\n<script type=\"text/javascript\">\n(function () {\n var skin_select = $('#customize-control-ppl-ninja-theme-options-skin').find('select');\n var custom_group = [\n '#accordion-section-custom_header_styles',\n '#accordion-section-custom_slider_styles',\n '#accordion-section-custom_footer_styles',\n '#accordion-section-custom_general_colors'\n ];\n\n skin_select.change(function () {\n if ($(this).val() == 4) {\n $(custom_group.join(',')).hide();\n } else {\n $(custom_group.join(',')).show();\n }\n });\n skin_select.change();\n}());\n</script>\n <?php\n }\n }\n\n $wp_customize->add_setting( 'ppl-ninja-theme-options-skin' );\n $wp_customize->add_section( 'ppl-ninja-theme-options', array(\n 'title' => __( 'Ninja Options', 'ppl' ),\n ) );\n\n // Add custom control.\n $wp_customize->add_control( new PPL_Ninja_Skin_Select_Customize_Control(\n $wp_customize, 'ppl-ninja-theme-options-skin', array(\n 'label' => __( 'Skin', 'ppl' ),\n 'section' => 'ppl-ninja-theme-options',\n 'choices' => array(\n '' => __( 'Select', 'ppl' ),\n 1 => __( 'One', 'ppl' ),\n 2 => __( 'Two', 'ppl' ),\n 3 => __( 'Three', 'ppl' ),\n 4 => __( 'Four', 'ppl' ),\n ),\n )\n ) );\n\n // Test data.\n foreach ( array( 'header_styles', 'slider_styles', 'footer_styles', 'general_colors' ) as $setting ) {\n $wp_customize->add_setting( 'custom_' . $setting . '-setting' );\n $wp_customize->add_section( 'custom_' . $setting, array(\n 'title' => sprintf( __( 'Ninja %s', 'ppl' ), $setting ),\n ) );\n $wp_customize->add_control( 'custom_' . $setting . '-setting', array (\n 'label' => __( 'Setting', 'td' ),\n 'section' => 'custom_' . $setting,\n ) );\n }\n} );\n</code></pre>\n\n<p>(also don't bother with any CSS).</p>\n"
},
{
"answer_id": 195612,
"author": "nadavy",
"author_id": 75695,
"author_profile": "https://wordpress.stackexchange.com/users/75695",
"pm_score": 0,
"selected": false,
"text": "<p>Although not a pretty solution, maybe you can sample it using window.setInterval() and once visible stop the interval and do whatever you want to do.</p>\n"
},
{
"answer_id": 195613,
"author": "Sisir",
"author_id": 3094,
"author_profile": "https://wordpress.stackexchange.com/users/3094",
"pm_score": 3,
"selected": true,
"text": "<p>So, far the problem was with the initial loading of the JS file. As i couldn't find any solution using the JS. The problem was not about the script loading rather then the execution timing. </p>\n\n<p>Anyways, The theme customizer looks into the global variable for which Panel/Section/Control it will show as active when it loads. </p>\n\n<h2>How to Make Sections/Controls/Panels Active/Deactive on initial loading</h2>\n\n<p>After spending hours into the core files I have found solution.</p>\n\n<ol>\n<li>For Panels use <code>customize_panel_active</code> filter. Passes two parameter <code>$active</code> boolean and <code>$panel</code> object.</li>\n<li>For Sections use <code>customize_section_active</code> filter. Passes two parameter <code>$active</code> boolean and <code>$section</code> object.</li>\n<li>For Controls use <code>customize_control_active</code> filter. Passes two parameter <code>$active</code> boolean and <code>$control</code> object.</li>\n</ol>\n\n<p><strong>Example:</strong> If I assume I have a panel and its id is <code>my_panel</code>. And I want to hide it if certain theme option is not set. </p>\n\n<pre><code>add_filter('customize_panel_active', 'maybe_panel_active', 10, 2);\n\nfunction maybe_panel_active($active, $panel){\n\n if($panel->id == 'my_panel' && !theme_option('certain_theme_option') ){\n $active = false;\n }\n\n return $active;\n}\n</code></pre>\n\n<p>That's about it! Pretty straight forward :)</p>\n\n<p><strong>Note:</strong> The solution is purely php. If anyone able to make it work by listening to the customizers JS events. I would be very interested on it as the question was initially intended for a JS solutions.</p>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3094/"
] |
I have a piece of JS code that I use show/hide customizer control groups depending on a select item value.
The code was working fine until recent wp update (not sure which version first broke this).
Here is the code for enqueuing the js file.
```
add_action('customize_controls_print_scripts', 'ppl_customize_controls_scripts');
function ppl_customize_controls_scripts(){
wp_register_script( 'ppl-customize-control', get_template_directory_uri().'/js/customizer-control.js', array('jquery'), 1, true);
wp_enqueue_script( 'ppl-customize-control' );
}
```
**The JS file**
```
jQuery(document).ready(function($){
var skin_select = $('#customize-control-ppl-ninja-theme-options-skin').find('select');
//alert(skin_select.attr('class'));
var selected_val = skin_select.children('option:selected').val();
var custom_group = [
'#accordion-section-custom_header_styles',
'#accordion-section-custom_slider_styles',
'#accordion-section-custom_footer_styles',
'#accordion-section-custom_general_colors'
];
if(selected_val != 4){
hide_custom_controls(custom_group);
}
skin_select.change(function(){
var val = $(this).val();
if(val != 4){
hide_custom_controls(custom_group);
}else{
show_custom_controls(custom_group);
}
});
function hide_custom_controls(custom_group){
var selector = custom_group.join(',');
$(selector).hide();
}
function show_custom_controls(custom_group){
var selector = custom_group.join(',');
$(selector).show();
}
});
```
**The problem is**, JS loads and hides the customizer control section just fine with inline css `display:none`. Then the cusomizer js script revises it and update the inline css to `display:list-item` which makes them visible. So, I need to run the JS code later after the customizer loads fully.
I looked into customizer script in wp-includes directory but haven't find anything that I can use. Perhaps I missed something.
Further Information
-------------------
1. The code that revising the css can be found in [`/wp-admin/js/customize-controls.js`](https://core.trac.wordpress.org/browser/trunk/src/wp-admin/js/customize-controls.js#L2584).
2. The script is using the `ready` event to add class and revise visibility of panels, sections and controls. But I am unable to add listener to that event.
3. The property activePanels, activeSections, activeControls are set from PHP from the file [`/wp-admin/customize.php`](https://core.trac.wordpress.org/browser/trunk/src/wp-admin/customize.php#L313) I have found no way to overwrite that variable as you can see it is printed just before the body tag ends.
So, the possible solution is perhaps finding a way to hook into the `ready` event.
|
So, far the problem was with the initial loading of the JS file. As i couldn't find any solution using the JS. The problem was not about the script loading rather then the execution timing.
Anyways, The theme customizer looks into the global variable for which Panel/Section/Control it will show as active when it loads.
How to Make Sections/Controls/Panels Active/Deactive on initial loading
-----------------------------------------------------------------------
After spending hours into the core files I have found solution.
1. For Panels use `customize_panel_active` filter. Passes two parameter `$active` boolean and `$panel` object.
2. For Sections use `customize_section_active` filter. Passes two parameter `$active` boolean and `$section` object.
3. For Controls use `customize_control_active` filter. Passes two parameter `$active` boolean and `$control` object.
**Example:** If I assume I have a panel and its id is `my_panel`. And I want to hide it if certain theme option is not set.
```
add_filter('customize_panel_active', 'maybe_panel_active', 10, 2);
function maybe_panel_active($active, $panel){
if($panel->id == 'my_panel' && !theme_option('certain_theme_option') ){
$active = false;
}
return $active;
}
```
That's about it! Pretty straight forward :)
**Note:** The solution is purely php. If anyone able to make it work by listening to the customizers JS events. I would be very interested on it as the question was initially intended for a JS solutions.
|
193,845 |
<p>I am looking for a way to edit the link that get inserted in the editor when the user choose to add a media. The goal would be to add a class with the media type (pdf) in the link.</p>
<p>I know how to get the mime type but I am not sure which hook to use to retrieve the link before it gets inserted. Could you point me in the right direction?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 193847,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 1,
"selected": false,
"text": "<p><strong>This is not the answer but just the hint.</strong></p>\n\n<p><code>media_send_to_editor</code> \nshould be the hook that should help you. Not sure how but came across this while searching for my problem</p>\n\n<p>I would have commented but still 4 points short, so unable to comment</p>\n\n<p>All the best</p>\n"
},
{
"answer_id": 193853,
"author": "Pipo",
"author_id": 54879,
"author_profile": "https://wordpress.stackexchange.com/users/54879",
"pm_score": 3,
"selected": true,
"text": "<p>So thanks to @amritanshu and @wycks <a href=\"https://gist.github.com/wycks/2176359\" rel=\"nofollow\">github's code</a>, here is the solution for those in need to add a class with the media type to the attachment url before it gets inserted in the editor :</p>\n\n<pre><code>if ( ! function_exists( 'epc_add_class_pdf' ) ) :\n\n function epc_add_class_pdf( $html, $id ) {\n\n $attachment = get_post( $id );\n $mime_type = $attachment->post_mime_type;\n\n // I only needed PDF but you can use whatever mime_type you need\n if ( $mime_type == 'application/pdf' ) {\n $src = wp_get_attachment_url( $id );\n $html = '<a class=\"pdf\" href=\"'. $src .'\">'. $attachment->post_title .'</a>';\n }\n\n return $html;\n}\nendif;\nadd_filter('media_send_to_editor', 'epc_add_class_pdf', 20, 3);\n</code></pre>\n"
},
{
"answer_id": 193856,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a shorter way to do it (PHP 5.4+):</p>\n\n<pre><code>add_filter( 'media_send_to_editor', function( $html, $send_id, $attachment )\n{\n $class = wp_check_filetype( $attachment['url'] )['ext'];\n return str_ireplace( '<a href', sprintf( '<a class=\"%s\" href',$class ? $class : 'unknown' ), $html );\n}, 10, 3 );\n</code></pre>\n\n<p>where we get the attachment's info from the third input argument. </p>\n\n<p>We could also use the mime type data, from <code>wp_check_filetype()</code>, instead of the extension.</p>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193845",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54879/"
] |
I am looking for a way to edit the link that get inserted in the editor when the user choose to add a media. The goal would be to add a class with the media type (pdf) in the link.
I know how to get the mime type but I am not sure which hook to use to retrieve the link before it gets inserted. Could you point me in the right direction?
Thanks!
|
So thanks to @amritanshu and @wycks [github's code](https://gist.github.com/wycks/2176359), here is the solution for those in need to add a class with the media type to the attachment url before it gets inserted in the editor :
```
if ( ! function_exists( 'epc_add_class_pdf' ) ) :
function epc_add_class_pdf( $html, $id ) {
$attachment = get_post( $id );
$mime_type = $attachment->post_mime_type;
// I only needed PDF but you can use whatever mime_type you need
if ( $mime_type == 'application/pdf' ) {
$src = wp_get_attachment_url( $id );
$html = '<a class="pdf" href="'. $src .'">'. $attachment->post_title .'</a>';
}
return $html;
}
endif;
add_filter('media_send_to_editor', 'epc_add_class_pdf', 20, 3);
```
|
193,850 |
<p>Original question: <a href="https://wordpress.stackexchange.com/questions/14881/seperating-custom-post-search-results">Seperating Custom Post Search Results</a></p>
<p>I've tried to implement this code to my website, but i have some problem with it.
What i've changed is i've added another switch for third post type, as follows:</p>
<pre><code><?php if (have_posts()) : ?>
<?php
$last_type = "";
$typecount = 0;
while (have_posts()) :
the_post();
if ($last_type != $post->post_type) {
$typecount = $typecount + 1;
if ($typecount > 1) {
echo '</div><!-- close container -->'; //close type container
}
// save the post type.
$last_type = $post->post_type;
//open type container
switch ($post->post_type) {
case 'post':
echo "<div class=\"postsearch container\"><h2>Blog Results</h2>";
break;
case 'partner':
echo "<div class=\"partnersearch container\"><h2>Partner Search Results</h2>";
break;
case 'fiches_pratiques':
echo "<div class=\"lessonsearch container\"><h2>lesson Search Results</h2>";
break;
}
}
?>
<?php if ('post' == get_post_type()) : ?>
<li class="post"><?php the_title(); ?></li>
<?php endif; ?>
<?php if ('partner' == get_post_type()) : ?>
<li class="partner"><?php the_title(); ?></li>
<?php endif; ?>
<?php if ('lesson' == get_post_type()) : ?>
<li class="lesson"><?php the_title(); ?></li>
<?php endif; ?>
<?php endwhile; ?>
<?php else : ?>
<div class="open-a-div">
<p>No results found.</p>
<?php endif; ?>
</code></pre>
<p>This code results in following:</p>
<blockquote>
<p><strong>Lessons Search Results</strong></p>
<p>Lesson 1 Lesson 4 Lesson 3</p>
<p><strong>Blog Results</strong></p>
<p>Test sub</p>
<p><strong>Partner Search Results</strong></p>
<p>Fourth partner</p>
<p><strong>Blog Results</strong></p>
<p>Lorem ipsum Wave 2.0 Web & Tech Cloud Open Container Project</p>
</blockquote>
<p>As you can notice, the blog results section is doubled.
Any suggestions on what might be the problem?</p>
<p>Installed search plugins:
Relevanssi</p>
<p><strong>NOTE:</strong> without Relevanssi (but with Search Everything plugin) it shows it in a proper way, but Search Everything plugin doesn't allow multiple terms search, which is a must have in my case.</p>
<p>Latest Wordpress version.</p>
<p>Thank you in advance.</p>
|
[
{
"answer_id": 193884,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Here is an idea, sort your your loop before it executes. Your current issue is just this. You will see that the type of sorting (<em>if I'm correct where I believe your order is not alphabetical according to post type</em>) is not possible natively, so we need a work-around (<em>even if you just need post types sorted alphabetically, the native way still lack proper functionality</em>). This is where <code>usort()</code> comes in, we can sort the post type post in any order we want. This will be done inside the <code>the_posts</code> filter</p>\n\n<p>I can show you both examples. <strong>NOTE:</strong> The code sample requires at least PHP 5.4+, which should be your minimum version now. All versions before 5.4 is EOL'ed, not supported and therefor a huge security risk if you are still using those versions. </p>\n\n<h2>SORT BY CUSTOM POST TYPE ORDER</h2>\n\n<pre><code>add_filter( 'the_posts', function( $posts, $q ) \n{\n if( $q->is_main_query() && $q->is_search() ) \n {\n usort( $posts, function( $a, $b ){\n /**\n * Sort by post type. If the post type between two posts are the same\n * sort by post date. Make sure you change your post types according to \n * your specific post types. This is my post types on my test site\n */\n $post_types = [\n 'event_type' => 1,\n 'post' => 2,\n 'cameras' => 3\n ]; \n if ( $post_types[$a->post_type] != $post_types[$b->post_type] ) {\n return $post_types[$a->post_type] - $post_types[$b->post_type];\n } else {\n return $a->post_date < $b->post_date; // Change to > if you need oldest posts first\n }\n });\n }\n return $posts;\n}, 10, 2 );\n</code></pre>\n\n<h2>SORT BY POST TYPE ALPHABETICAL ORDER</h2>\n\n<pre><code>add_filter( 'the_posts', function( $posts, $q ) \n{\n if( $q->is_main_query() && $q->is_search() ) \n {\n usort( $posts, function( $a, $b ){\n /**\n * Sort by post type. If the post type between two posts are the same\n * sort by post date. Be sure to change this accordingly\n */\n\n if ( $a->post_type != $b->post_type ) {\n return strcasecmp( \n $a->post_type, // Change these two values around to sort descending\n $b->post_type \n );\n } else {\n return $a->post_date < $b->post_date; // Change to > if you need oldest posts first\n }\n });\n }\n return $posts;\n}, 10, 2 );\n</code></pre>\n\n<p>Your posts should now be sorted by post type on your search page, that is, if you are not using a custom query in place of your main query. As for your code above, keep it as is, not necessary to make any adjustments to it </p>\n"
},
{
"answer_id": 193885,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>You are getting your post results in the order that the Relevanssi plugin thinks is correct. That is, you are getting the results in the most relevant order according to the plugin's logic (I don't know what that is exactly) which is the point of the plugin. </p>\n\n<p>Generally speaking, ordering by post type isn't that hard:</p>\n\n<pre><code>function orderby_type($orderby) {\n remove_filter('posts_orderby','orderby_type');\n global $wpdb;\n return $wpdb->posts.'.post_type';\n}\nadd_filter('posts_orderby','orderby_type');\n$args = array(\n 'post_type' => array('post','page','book'),\n 'orderby' => 'post_type'\n);\n$w = new WP_Query($args);\n</code></pre>\n\n<p>However, I'd expect that to break the \"relevant\" ordering the plugin is providing. In fact, anything you do is likely to break the \"relevance\" calculation to some extent. Something like the following should be about the best you can do:</p>\n\n<pre><code>function resort_posts($posts) {\n $sorted = $ret = array();\n foreach ($posts as $p) {\n $sorted[$p->post_type][] = $p;\n }\n foreach ($sorted as $s) {\n $ret = array_merge($ret,$s);\n }\n // verify\n// $pid = wp_list_pluck($posts,'ID');\n// $sid = wp_list_pluck($ret,'ID');\n// var_dump(array_diff($pid,$sid));\n return $ret;\n}\nadd_filter('the_posts','resort_posts');\n</code></pre>\n\n<p>You will need to figure out how to make that work with Relevanssi without also messing with all queries on the site (which it will do as written). I have never used that plugin so I can't say (plugin specific question are off topic as well, by the way)</p>\n"
},
{
"answer_id": 193892,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>Did you search the <a href=\"https://www.google.com/?q=relevanssi%2Bsort%2Bby%2Bpost%2Btype#q=relevanssi+sort+by+post+type\" rel=\"nofollow\">endless expanses of the internet </a>?</p>\n\n<p>Because the first entry on the SERP is an article at the relvanssi knowledge base, with the title »<a href=\"http://www.relevanssi.com/knowledge-base/separating-posts-by-post-type/\" rel=\"nofollow\">Separating posts by post type</a>«, sounds fitting to me. Below is the code for the proposed approach:</p>\n\n<pre><code>add_filter('relevanssi_hits_filter', 'separate_result_types');\nfunction separate_result_types($hits) {\n $types = array();\n\n // Split the post types in array $types\n if (!empty($hits)) {\n foreach ($hits[0] as $hit) {\n if (!is_array($types[$hit->post_type])) $types[$hit->post_type] = array(); \n array_push($types[$hit->post_type], $hit);\n }\n }\n\n // Merge back to $hits in the desired order\n $hits[0] = array_merge(\n $types['mycustomtypethatgoesfirst'], \n $types['thesecondmostimportanttype'], \n $types['post'], $types['pages']\n );\n return $hits;\n}\n</code></pre>\n\n<p><br>\n<em>Notes:</em> </p>\n\n<ul>\n<li>I did not do anything, but copying the code. </li>\n<li>I could not link the search with LMGTFY, apparently it is not considered to be nice (any more at least). Ok, I kind of - maybe even completely - get that, but seriously, do your research - pretty please :)</li>\n</ul>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55153/"
] |
Original question: [Seperating Custom Post Search Results](https://wordpress.stackexchange.com/questions/14881/seperating-custom-post-search-results)
I've tried to implement this code to my website, but i have some problem with it.
What i've changed is i've added another switch for third post type, as follows:
```
<?php if (have_posts()) : ?>
<?php
$last_type = "";
$typecount = 0;
while (have_posts()) :
the_post();
if ($last_type != $post->post_type) {
$typecount = $typecount + 1;
if ($typecount > 1) {
echo '</div><!-- close container -->'; //close type container
}
// save the post type.
$last_type = $post->post_type;
//open type container
switch ($post->post_type) {
case 'post':
echo "<div class=\"postsearch container\"><h2>Blog Results</h2>";
break;
case 'partner':
echo "<div class=\"partnersearch container\"><h2>Partner Search Results</h2>";
break;
case 'fiches_pratiques':
echo "<div class=\"lessonsearch container\"><h2>lesson Search Results</h2>";
break;
}
}
?>
<?php if ('post' == get_post_type()) : ?>
<li class="post"><?php the_title(); ?></li>
<?php endif; ?>
<?php if ('partner' == get_post_type()) : ?>
<li class="partner"><?php the_title(); ?></li>
<?php endif; ?>
<?php if ('lesson' == get_post_type()) : ?>
<li class="lesson"><?php the_title(); ?></li>
<?php endif; ?>
<?php endwhile; ?>
<?php else : ?>
<div class="open-a-div">
<p>No results found.</p>
<?php endif; ?>
```
This code results in following:
>
> **Lessons Search Results**
>
>
> Lesson 1 Lesson 4 Lesson 3
>
>
> **Blog Results**
>
>
> Test sub
>
>
> **Partner Search Results**
>
>
> Fourth partner
>
>
> **Blog Results**
>
>
> Lorem ipsum Wave 2.0 Web & Tech Cloud Open Container Project
>
>
>
As you can notice, the blog results section is doubled.
Any suggestions on what might be the problem?
Installed search plugins:
Relevanssi
**NOTE:** without Relevanssi (but with Search Everything plugin) it shows it in a proper way, but Search Everything plugin doesn't allow multiple terms search, which is a must have in my case.
Latest Wordpress version.
Thank you in advance.
|
Here is an idea, sort your your loop before it executes. Your current issue is just this. You will see that the type of sorting (*if I'm correct where I believe your order is not alphabetical according to post type*) is not possible natively, so we need a work-around (*even if you just need post types sorted alphabetically, the native way still lack proper functionality*). This is where `usort()` comes in, we can sort the post type post in any order we want. This will be done inside the `the_posts` filter
I can show you both examples. **NOTE:** The code sample requires at least PHP 5.4+, which should be your minimum version now. All versions before 5.4 is EOL'ed, not supported and therefor a huge security risk if you are still using those versions.
SORT BY CUSTOM POST TYPE ORDER
------------------------------
```
add_filter( 'the_posts', function( $posts, $q )
{
if( $q->is_main_query() && $q->is_search() )
{
usort( $posts, function( $a, $b ){
/**
* Sort by post type. If the post type between two posts are the same
* sort by post date. Make sure you change your post types according to
* your specific post types. This is my post types on my test site
*/
$post_types = [
'event_type' => 1,
'post' => 2,
'cameras' => 3
];
if ( $post_types[$a->post_type] != $post_types[$b->post_type] ) {
return $post_types[$a->post_type] - $post_types[$b->post_type];
} else {
return $a->post_date < $b->post_date; // Change to > if you need oldest posts first
}
});
}
return $posts;
}, 10, 2 );
```
SORT BY POST TYPE ALPHABETICAL ORDER
------------------------------------
```
add_filter( 'the_posts', function( $posts, $q )
{
if( $q->is_main_query() && $q->is_search() )
{
usort( $posts, function( $a, $b ){
/**
* Sort by post type. If the post type between two posts are the same
* sort by post date. Be sure to change this accordingly
*/
if ( $a->post_type != $b->post_type ) {
return strcasecmp(
$a->post_type, // Change these two values around to sort descending
$b->post_type
);
} else {
return $a->post_date < $b->post_date; // Change to > if you need oldest posts first
}
});
}
return $posts;
}, 10, 2 );
```
Your posts should now be sorted by post type on your search page, that is, if you are not using a custom query in place of your main query. As for your code above, keep it as is, not necessary to make any adjustments to it
|
193,851 |
<p>This is my code </p>
<pre><code><?php
global $wpdb;
$rows = $wpdb->get_results("SELECT `submit_time` AS 'Submitted', max( if( `field_name` = 'Salutation', `field_value` , NULL ) ) AS 'Salutation', max( if( `field_name` = 'First Name', `field_value` , NULL ) ) AS 'First Name', max( if( `field_name` = 'Last Name', `field_value` , NULL ) ) AS 'Last Name', max( if( `field_name` = 'Title', `field_value` , NULL ) ) AS 'Title'
FROM `wp_cf7dbplugin_submits`
WHERE `form_name` = 'Sign Up'
GROUP BY `submit_time`
ORDER BY `submit_time` DESC
LIMIT 0 , 100
");
foreach($rows as $a){
echo $a->field_value;//field value is col name
}
$wpdb->print_error();
?>
</code></pre>
<p>What I am doing wrong here ?</p>
|
[
{
"answer_id": 193884,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Here is an idea, sort your your loop before it executes. Your current issue is just this. You will see that the type of sorting (<em>if I'm correct where I believe your order is not alphabetical according to post type</em>) is not possible natively, so we need a work-around (<em>even if you just need post types sorted alphabetically, the native way still lack proper functionality</em>). This is where <code>usort()</code> comes in, we can sort the post type post in any order we want. This will be done inside the <code>the_posts</code> filter</p>\n\n<p>I can show you both examples. <strong>NOTE:</strong> The code sample requires at least PHP 5.4+, which should be your minimum version now. All versions before 5.4 is EOL'ed, not supported and therefor a huge security risk if you are still using those versions. </p>\n\n<h2>SORT BY CUSTOM POST TYPE ORDER</h2>\n\n<pre><code>add_filter( 'the_posts', function( $posts, $q ) \n{\n if( $q->is_main_query() && $q->is_search() ) \n {\n usort( $posts, function( $a, $b ){\n /**\n * Sort by post type. If the post type between two posts are the same\n * sort by post date. Make sure you change your post types according to \n * your specific post types. This is my post types on my test site\n */\n $post_types = [\n 'event_type' => 1,\n 'post' => 2,\n 'cameras' => 3\n ]; \n if ( $post_types[$a->post_type] != $post_types[$b->post_type] ) {\n return $post_types[$a->post_type] - $post_types[$b->post_type];\n } else {\n return $a->post_date < $b->post_date; // Change to > if you need oldest posts first\n }\n });\n }\n return $posts;\n}, 10, 2 );\n</code></pre>\n\n<h2>SORT BY POST TYPE ALPHABETICAL ORDER</h2>\n\n<pre><code>add_filter( 'the_posts', function( $posts, $q ) \n{\n if( $q->is_main_query() && $q->is_search() ) \n {\n usort( $posts, function( $a, $b ){\n /**\n * Sort by post type. If the post type between two posts are the same\n * sort by post date. Be sure to change this accordingly\n */\n\n if ( $a->post_type != $b->post_type ) {\n return strcasecmp( \n $a->post_type, // Change these two values around to sort descending\n $b->post_type \n );\n } else {\n return $a->post_date < $b->post_date; // Change to > if you need oldest posts first\n }\n });\n }\n return $posts;\n}, 10, 2 );\n</code></pre>\n\n<p>Your posts should now be sorted by post type on your search page, that is, if you are not using a custom query in place of your main query. As for your code above, keep it as is, not necessary to make any adjustments to it </p>\n"
},
{
"answer_id": 193885,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>You are getting your post results in the order that the Relevanssi plugin thinks is correct. That is, you are getting the results in the most relevant order according to the plugin's logic (I don't know what that is exactly) which is the point of the plugin. </p>\n\n<p>Generally speaking, ordering by post type isn't that hard:</p>\n\n<pre><code>function orderby_type($orderby) {\n remove_filter('posts_orderby','orderby_type');\n global $wpdb;\n return $wpdb->posts.'.post_type';\n}\nadd_filter('posts_orderby','orderby_type');\n$args = array(\n 'post_type' => array('post','page','book'),\n 'orderby' => 'post_type'\n);\n$w = new WP_Query($args);\n</code></pre>\n\n<p>However, I'd expect that to break the \"relevant\" ordering the plugin is providing. In fact, anything you do is likely to break the \"relevance\" calculation to some extent. Something like the following should be about the best you can do:</p>\n\n<pre><code>function resort_posts($posts) {\n $sorted = $ret = array();\n foreach ($posts as $p) {\n $sorted[$p->post_type][] = $p;\n }\n foreach ($sorted as $s) {\n $ret = array_merge($ret,$s);\n }\n // verify\n// $pid = wp_list_pluck($posts,'ID');\n// $sid = wp_list_pluck($ret,'ID');\n// var_dump(array_diff($pid,$sid));\n return $ret;\n}\nadd_filter('the_posts','resort_posts');\n</code></pre>\n\n<p>You will need to figure out how to make that work with Relevanssi without also messing with all queries on the site (which it will do as written). I have never used that plugin so I can't say (plugin specific question are off topic as well, by the way)</p>\n"
},
{
"answer_id": 193892,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>Did you search the <a href=\"https://www.google.com/?q=relevanssi%2Bsort%2Bby%2Bpost%2Btype#q=relevanssi+sort+by+post+type\" rel=\"nofollow\">endless expanses of the internet </a>?</p>\n\n<p>Because the first entry on the SERP is an article at the relvanssi knowledge base, with the title »<a href=\"http://www.relevanssi.com/knowledge-base/separating-posts-by-post-type/\" rel=\"nofollow\">Separating posts by post type</a>«, sounds fitting to me. Below is the code for the proposed approach:</p>\n\n<pre><code>add_filter('relevanssi_hits_filter', 'separate_result_types');\nfunction separate_result_types($hits) {\n $types = array();\n\n // Split the post types in array $types\n if (!empty($hits)) {\n foreach ($hits[0] as $hit) {\n if (!is_array($types[$hit->post_type])) $types[$hit->post_type] = array(); \n array_push($types[$hit->post_type], $hit);\n }\n }\n\n // Merge back to $hits in the desired order\n $hits[0] = array_merge(\n $types['mycustomtypethatgoesfirst'], \n $types['thesecondmostimportanttype'], \n $types['post'], $types['pages']\n );\n return $hits;\n}\n</code></pre>\n\n<p><br>\n<em>Notes:</em> </p>\n\n<ul>\n<li>I did not do anything, but copying the code. </li>\n<li>I could not link the search with LMGTFY, apparently it is not considered to be nice (any more at least). Ok, I kind of - maybe even completely - get that, but seriously, do your research - pretty please :)</li>\n</ul>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193851",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75547/"
] |
This is my code
```
<?php
global $wpdb;
$rows = $wpdb->get_results("SELECT `submit_time` AS 'Submitted', max( if( `field_name` = 'Salutation', `field_value` , NULL ) ) AS 'Salutation', max( if( `field_name` = 'First Name', `field_value` , NULL ) ) AS 'First Name', max( if( `field_name` = 'Last Name', `field_value` , NULL ) ) AS 'Last Name', max( if( `field_name` = 'Title', `field_value` , NULL ) ) AS 'Title'
FROM `wp_cf7dbplugin_submits`
WHERE `form_name` = 'Sign Up'
GROUP BY `submit_time`
ORDER BY `submit_time` DESC
LIMIT 0 , 100
");
foreach($rows as $a){
echo $a->field_value;//field value is col name
}
$wpdb->print_error();
?>
```
What I am doing wrong here ?
|
Here is an idea, sort your your loop before it executes. Your current issue is just this. You will see that the type of sorting (*if I'm correct where I believe your order is not alphabetical according to post type*) is not possible natively, so we need a work-around (*even if you just need post types sorted alphabetically, the native way still lack proper functionality*). This is where `usort()` comes in, we can sort the post type post in any order we want. This will be done inside the `the_posts` filter
I can show you both examples. **NOTE:** The code sample requires at least PHP 5.4+, which should be your minimum version now. All versions before 5.4 is EOL'ed, not supported and therefor a huge security risk if you are still using those versions.
SORT BY CUSTOM POST TYPE ORDER
------------------------------
```
add_filter( 'the_posts', function( $posts, $q )
{
if( $q->is_main_query() && $q->is_search() )
{
usort( $posts, function( $a, $b ){
/**
* Sort by post type. If the post type between two posts are the same
* sort by post date. Make sure you change your post types according to
* your specific post types. This is my post types on my test site
*/
$post_types = [
'event_type' => 1,
'post' => 2,
'cameras' => 3
];
if ( $post_types[$a->post_type] != $post_types[$b->post_type] ) {
return $post_types[$a->post_type] - $post_types[$b->post_type];
} else {
return $a->post_date < $b->post_date; // Change to > if you need oldest posts first
}
});
}
return $posts;
}, 10, 2 );
```
SORT BY POST TYPE ALPHABETICAL ORDER
------------------------------------
```
add_filter( 'the_posts', function( $posts, $q )
{
if( $q->is_main_query() && $q->is_search() )
{
usort( $posts, function( $a, $b ){
/**
* Sort by post type. If the post type between two posts are the same
* sort by post date. Be sure to change this accordingly
*/
if ( $a->post_type != $b->post_type ) {
return strcasecmp(
$a->post_type, // Change these two values around to sort descending
$b->post_type
);
} else {
return $a->post_date < $b->post_date; // Change to > if you need oldest posts first
}
});
}
return $posts;
}, 10, 2 );
```
Your posts should now be sorted by post type on your search page, that is, if you are not using a custom query in place of your main query. As for your code above, keep it as is, not necessary to make any adjustments to it
|
193,852 |
<p>I've made a function to hook after the_content. This is only working on certain pages/posts. It's working on the default template but not on my custom one's.</p>
<pre><code>function insertFootNote($content) {
$content.= "<div>";
$content.="additional content";
$content.= "</div>";
return $content;
}
add_filter ('the_content', 'insertCpontent');
</code></pre>
<p>In my custom page template I haven the following code</p>
<pre><code><?php if(have_posts()): ?>
<?php get_template_part( 'part', 'addressbook' ); ?>
<?php endif; ?>
</code></pre>
<p>in the template('part-addressbook.php) I have the following.</p>
<pre><code> echo '<div class="category-description"><p>'.get_the_content().'</p></div>';
</code></pre>
<p>On this template part the hook is not working although i'm using the_content/get_the_content function</p>
<p>Why does the hook does not work in this case?</p>
|
[
{
"answer_id": 193855,
"author": "M-R",
"author_id": 17061,
"author_profile": "https://wordpress.stackexchange.com/users/17061",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_the_content\" rel=\"nofollow\">get_the_content</a> do not apply the_content filter. You have to apply it after receiving contents like following</p>\n\n<pre><code><?php apply_filters('the_content',get_the_content( $more_link_text, $stripteaser, $more_file )) ?>\n</code></pre>\n\n<p>It is also detailed at the bottom of <a href=\"https://codex.wordpress.org/Function_Reference/get_the_content\" rel=\"nofollow\">codex page</a></p>\n"
},
{
"answer_id": 193927,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>You are already <code>echo</code>ing the data. Just use <code>the_content()</code>:</p>\n\n<pre><code>echo '<div class=\"category-description\"><p>',the_content(),'</p></div>';\n</code></pre>\n\n<p>Please note: those are <strong><em>commas</em></strong> not periods. <code>echo</code> will accept multiple parameters separated by commas and you will not see the odd results you get if you try to concatenate. The above is functionally the same as:</p>\n\n<pre><code>echo '<div class=\"category-description\"><p>';\n the_content();\necho '</p></div>';\n</code></pre>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193852",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31706/"
] |
I've made a function to hook after the\_content. This is only working on certain pages/posts. It's working on the default template but not on my custom one's.
```
function insertFootNote($content) {
$content.= "<div>";
$content.="additional content";
$content.= "</div>";
return $content;
}
add_filter ('the_content', 'insertCpontent');
```
In my custom page template I haven the following code
```
<?php if(have_posts()): ?>
<?php get_template_part( 'part', 'addressbook' ); ?>
<?php endif; ?>
```
in the template('part-addressbook.php) I have the following.
```
echo '<div class="category-description"><p>'.get_the_content().'</p></div>';
```
On this template part the hook is not working although i'm using the\_content/get\_the\_content function
Why does the hook does not work in this case?
|
[get\_the\_content](https://codex.wordpress.org/Function_Reference/get_the_content) do not apply the\_content filter. You have to apply it after receiving contents like following
```
<?php apply_filters('the_content',get_the_content( $more_link_text, $stripteaser, $more_file )) ?>
```
It is also detailed at the bottom of [codex page](https://codex.wordpress.org/Function_Reference/get_the_content)
|
193,880 |
<p>how do you get the author's username?
I'm using this code
"get_the_author()"
I wanted to change this into author's username, instead of author's name.</p>
<p>Thankyou</p>
|
[
{
"answer_id": 193925,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>In the Loop, it would be:</p>\n\n<pre><code>$authorname = get_the_author_meta('user_nicename');\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>$authorname = get_the_author_meta('displayname');\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>$authorname = get_the_author_meta('nickname');\n</code></pre>\n\n<p>Or any field that <a href=\"https://codex.wordpress.org/Function_Reference/get_the_author_meta\" rel=\"nofollow\"><code>get_the_author_meta()</code></a> accepts.</p>\n\n<pre><code>$authorname = get_the_author_meta('user_nicename',123);\n</code></pre>\n\n<p>If you just need to <code>echo</code> the name just use <a href=\"https://codex.wordpress.org/Function_Reference/the_author_meta\" rel=\"nofollow\"><code>the_author_meta()</code></a> instead:</p>\n\n<pre><code>the_author_meta('user_nicename',123);\n</code></pre>\n"
},
{
"answer_id": 193940,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>I found something that is better help you.</p>\n<p>We have multiple option to get author name provided by WP.\n1)</p>\n<pre><code><?php get_the_author_meta( $field, $userID ); ?> \nVia this function you can get current user auther name by:\n<?php $auth_name = get_the_author_meta( 'display_name' ); ?>\n</code></pre>\n<p>OR if you pass <code>$userID</code> as secont param then you can get that use field like:</p>\n<pre><code><?php $auth_name = get_the_author_meta( 'display_name', $userID ); ?>\n</code></pre>\n<p>There is different fields that you can fetch via this function for respected author information:\n<code>display_name</code>, <code>nickname</code>, <code>first_name</code>, <code>last_name</code> and <a href=\"https://developer.wordpress.org/reference/functions/get_the_author_meta/\" rel=\"nofollow noreferrer\">Many more</a></p>\n<ol start=\"2\">\n<li><code><?php get_userdata($userID ); ?></code></li>\n</ol>\n<p>This is done by setting up a variable called <code>$currauth</code> (Current Author). The usual way to do this is to put the following lines before the loop in your template file:</p>\n<pre><code><?php\n$currauth = (isset($_GET['author_name'])) ? get_user_by('slug', $_GET['author_name']) : get_userdata($_GET['author']);\n?>\n</code></pre>\n<p>Or this example that only works in WordPress Version 2.8 and higher:</p>\n<pre><code><?php\n$currauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author'));\n?>\n</code></pre>\n<p>Now that you have the $currauth variable set up, you can use it to display all kinds of information about the author whose page is being displayed. Now you have below choice to use:</p>\n<p>//For display name</p>\n<pre><code>$currauth->display_name;\n</code></pre>\n<p>//For First Name</p>\n<pre><code>$currauth->first_name\n</code></pre>\n<p>//For Last Name</p>\n<pre><code>$currauth->last_name\n</code></pre>\n<p>//For Nick Name</p>\n<pre><code>$currauth->nickname\n</code></pre>\n<p>and <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow noreferrer\">Many more</a></p>\n<p>Let me know if you face any further query regarding this.</p>\n<p>Thanks!</p>\n"
},
{
"answer_id": 240897,
"author": "Nanhe Kumar",
"author_id": 31624,
"author_profile": "https://wordpress.stackexchange.com/users/31624",
"pm_score": 0,
"selected": false,
"text": "<p>In the Loop </p>\n\n<pre><code>$username=get_the_author_meta('user_nicename');\n</code></pre>\n\n<p>Outside of Loop (Suppose $user_id=1)</p>\n\n<pre><code>$username=get_the_author_meta( 'user_nicename', $user_id );\n</code></pre>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_userdata/\" rel=\"nofollow\">get_userdata</a> function.</p>\n\n<pre><code>$username=get_userdata($user_id)->user_nicename;\n</code></pre>\n\n<p>you can use <a href=\"https://developer.wordpress.org/reference/functions/get_user_by/\" rel=\"nofollow\">get_user_by</a> function </p>\n\n<pre><code>$username=get_user_by( 'id', $user_id )->user_nicename;\n</code></pre>\n"
},
{
"answer_id": 327899,
"author": "faddah",
"author_id": 160712,
"author_profile": "https://wordpress.stackexchange.com/users/160712",
"pm_score": 1,
"selected": false,
"text": "<p>Regarding @s_ha_dum answer above, he is correct, but it's no longer <code>get_the_author_meta('displayname');</code>, it should be: <code>get_the_author_meta('display_name');</code>.</p>\n\n<p>See: <a href=\"https://developer.wordpress.org/reference/functions/get_the_author_meta/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_author_meta/</a></p>\n"
},
{
"answer_id": 375341,
"author": "makeshyft_tom",
"author_id": 194965,
"author_profile": "https://wordpress.stackexchange.com/users/194965",
"pm_score": 1,
"selected": false,
"text": "<p>The actual answer to your question is:</p>\n<pre><code>get_the_author_meta('user_login');\n</code></pre>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75855/"
] |
how do you get the author's username?
I'm using this code
"get\_the\_author()"
I wanted to change this into author's username, instead of author's name.
Thankyou
|
In the Loop, it would be:
```
$authorname = get_the_author_meta('user_nicename');
```
Or:
```
$authorname = get_the_author_meta('displayname');
```
Or:
```
$authorname = get_the_author_meta('nickname');
```
Or any field that [`get_the_author_meta()`](https://codex.wordpress.org/Function_Reference/get_the_author_meta) accepts.
```
$authorname = get_the_author_meta('user_nicename',123);
```
If you just need to `echo` the name just use [`the_author_meta()`](https://codex.wordpress.org/Function_Reference/the_author_meta) instead:
```
the_author_meta('user_nicename',123);
```
|
193,894 |
<p>I don't know what I'm doing wrong here. I created a page with accordians, the jquery script loads just fine but when I link the CSS stylesheet, no CSS shows up. It is not an external stylesheet, I posted the CSS in the same stylesheet used for all pages which is styles.css</p>
<p>The page </p>
<p><a href="http://scarincihollenbeck.com/law-practices/" rel="nofollow">http://scarincihollenbeck.com/law-practices/</a></p>
<p>When it's inspected the stylesheet says it loaded but It doesn't display anything. Been stuck for hours, any help would be appreciated.</p>
<pre><code>*:before,
*:after {
-webkit-border-sizing: border-box;
-moz-border-sizing: border-box;
border-sizing: border-box;
margin: 0px;
padding: 0px;
}
.container-lawpractice {
width: 90%;
margin: -10px auto;
}
.container-lawpractice > ul {
list-style: none;
padding: 0px;
margin: 0 0 20px 0;
}
.dropdown a {
text-decoration: none;
}
.dropdown [data-toggle="dropdown"] {
position: relative;
display: block;
color: white;
background: #d02422;
-moz-box-shadow: 0 1px 0 #1a1a1a inset, 0 -1px 0 black inset;
-webkit-box-shadow: 0 1px 0 #1a1a1a inset, 0 -1px 0 black inset;
box-shadow: 0 1px 0 #1a1a1a inset, 0 -1px 0 black inset;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3);
padding: 10px 17px;
text-align: left;
border-left: 10px solid black;
font-family: 'DIN1451W01-Mittelschrif', Arial, Helvetica, sans-serif;
font-size: 15px;
font-weight: 600;
}
.dropdown [data-toggle="dropdown"]:hover {
background: #121211;
color: white;
border-left: 10px solid #d02422;
}
.dropdown .icon-arrow {
position: absolute;
display: block;
font-size: 0.8em;
color: #fff;
top: 14px;
right: 10px;
}
.dropdown .icon-arrow.open {
-moz-transform: rotate(-180deg);
-ms-transform: rotate(-180deg);
-webkit-transform: rotate(-180deg);
transform: rotate(-180deg);
-moz-transition: -moz-transform 0.6s;
-o-transition: -o-transform 0.6s;
-webkit-transition: -webkit-transform 0.6s;
transition: transform 0.6s;
}
.dropdown .icon-arrow.close {
-moz-transform: rotate(0deg);
-ms-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
-moz-transition: -moz-transform 0.6s;
-o-transition: -o-transform 0.6s;
-webkit-transition: -webkit-transform 0.6s;
transition: transform 0.6s;
}
.dropdown .icon-arrow:before {
content: '\25BC';
}
.dropdown .dropdown-menu {
max-height: 0;
overflow: hidden;
list-style: none;
padding: 0;
margin: 0;
}
.dropdown .dropdown-menu li {
padding: 0;
}
.dropdown .dropdown-menu li a {
display: block;
color: black;
background: #EEE;
-moz-box-shadow: 0 1px 0 white inset, 0 -1px 0 #d4d4d4 inset;
-webkit-box-shadow: 0 1px 0 white inset, 0 -1px 0 #d4d4d4 inset;
box-shadow: 0 1px 0 white inset, 0 -1px 0 #d4d4d4 inset;
text-shadow: 0 -1px 0 rgba(255, 255, 255, 0.3);
padding: 10px 10px;
font-size: 13px;
text-indent: 30px;
font-family: 'DIN1451W01-Mittelschrif', Arial, Helvetica, sans-serif;
border-left: 10px solid #d02422;
font-weight: 500;
}
.dropdown .dropdown-menu li a:hover {
background: #FFFFFF;
color: #d02422;
font-weight: 700;
border-left: 10px solid black;
}
.dropdown .show,
.dropdown .hide {
-moz-transform-origin: 50% 0%;
-ms-transform-origin: 50% 0%;
-webkit-transform-origin: 50% 0%;
transform-origin: 50% 0%;
}
.dropdown .show {
display: block;
max-height: 9999px;
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
animation: showAnimation 0.5s ease-in-out;
-moz-animation: showAnimation 0.5s ease-in-out;
-webkit-animation: showAnimation 0.5s ease-in-out;
-moz-transition: max-height 1s ease-in-out;
-o-transition: max-height 1s ease-in-out;
-webkit-transition: max-height 1s ease-in-out;
transition: max-height 1s ease-in-out;
}
.dropdown .hide {
max-height: 0;
-moz-transform: scaleY(0);
-ms-transform: scaleY(0);
-webkit-transform: scaleY(0);
transform: scaleY(0);
animation: hideAnimation 0.4s ease-out;
-moz-animation: hideAnimation 0.4s ease-out;
-webkit-animation: hideAnimation 0.4s ease-out;
-moz-transition: max-height 0.6s ease-out;
-o-transition: max-height 0.6s ease-out;
-webkit-transition: max-height 0.6s ease-out;
transition: max-height 0.6s ease-out;
}
@keyframes showAnimation {
0% {
-moz-transform: scaleY(0.1);
-ms-transform: scaleY(0.1);
-webkit-transform: scaleY(0.1);
transform: scaleY(0.1);
}
40% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
100% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
}
@-moz-keyframes showAnimation {
0% {
-moz-transform: scaleY(0.1);
-ms-transform: scaleY(0.1);
-webkit-transform: scaleY(0.1);
transform: scaleY(0.1);
}
40% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
100% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
}
@-webkit-keyframes showAnimation {
0% {
-moz-transform: scaleY(0.1);
-ms-transform: scaleY(0.1);
-webkit-transform: scaleY(0.1);
transform: scaleY(0.1);
}
40% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
100% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
}
@keyframes hideAnimation {
0% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(0);
-ms-transform: scaleY(0);
-webkit-transform: scaleY(0);
transform: scaleY(0);
}
}
@-moz-keyframes hideAnimation {
0% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(0);
-ms-transform: scaleY(0);
-webkit-transform: scaleY(0);
transform: scaleY(0);
}
}
@-webkit-keyframes hideAnimation {
0% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(0);
-ms-transform: scaleY(0);
-webkit-transform: scaleY(0);
transform: scaleY(0);
}
}
.whole-body {
position: relative;
max-width: 1200px;
margin: 0 auto;
}
.full-body {
position: relative;
max-width: 1200px;
margin: 5% auto;
}
.row {
width: 100%;
margin-left: 5%;
}
.col-sm-6 {
width: 30%;
float: left;
margin: 5% 0% 0 0;
}
.box-hover{
display: none;
width: 75%;
background-color: rgb(208, 36, 34);
border: 1px solid #fff;
height: 200px;
margin: 15% 0 0 15%;
padding: 5%;
}
@media screen and (max-width: 600px) {
.col-sm-6{width:80%;}
.container{width:80%;}
</code></pre>
<p>I'm also running a bootstrap script if that's any importance. Been stuck for hours, any help would be appreciated.</p>
|
[
{
"answer_id": 193896,
"author": "jpburn",
"author_id": 75868,
"author_profile": "https://wordpress.stackexchange.com/users/75868",
"pm_score": -1,
"selected": false,
"text": "<p>Please try this instead. Replace your css by : <code><link rel=\"stylesheet\" type=\"text/css\" href=\"<?php echo get_template_directory_uri(); ?>/assets/stylesheets/styles.css\" /></code> in the head section</p>\n"
},
{
"answer_id": 193911,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 1,
"selected": true,
"text": "<p>Add the CSS to your child themes style.css file or load it using wp_enqueue_scripts</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpsites_load_custom_styles' );\nfunction wpsites_load_custom_styles() {\n\n wp_register_style( 'custom-css', get_stylesheet_directory_uri() . '/your-style.css', false, '1.0.0' );\n wp_enqueue_style( 'custom-css' );\n\n}\n</code></pre>\n\n<p><a href=\"http://wpsites.net/wordpress-themes/second-style-sheet-theme/\" rel=\"nofollow\">Source</a></p>\n"
},
{
"answer_id": 193914,
"author": "Ray Flores",
"author_id": 29355,
"author_profile": "https://wordpress.stackexchange.com/users/29355",
"pm_score": -1,
"selected": false,
"text": "<p>You could add to your functions.php (in child theme) a reference to just that one page (is_page('law-practices')) and enqueue just for that one page:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'law_practice_enqueue_style' );\nfunction law_practice_enqueue_style(){\n if (is_page('law-practices')){\n wp_register_style( 'law-styles', get_template_directory_uri() . 'law-style.css', false );\n wp_enqueue_style('law-style');\n }\n\n}\n</code></pre>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193894",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74889/"
] |
I don't know what I'm doing wrong here. I created a page with accordians, the jquery script loads just fine but when I link the CSS stylesheet, no CSS shows up. It is not an external stylesheet, I posted the CSS in the same stylesheet used for all pages which is styles.css
The page
<http://scarincihollenbeck.com/law-practices/>
When it's inspected the stylesheet says it loaded but It doesn't display anything. Been stuck for hours, any help would be appreciated.
```
*:before,
*:after {
-webkit-border-sizing: border-box;
-moz-border-sizing: border-box;
border-sizing: border-box;
margin: 0px;
padding: 0px;
}
.container-lawpractice {
width: 90%;
margin: -10px auto;
}
.container-lawpractice > ul {
list-style: none;
padding: 0px;
margin: 0 0 20px 0;
}
.dropdown a {
text-decoration: none;
}
.dropdown [data-toggle="dropdown"] {
position: relative;
display: block;
color: white;
background: #d02422;
-moz-box-shadow: 0 1px 0 #1a1a1a inset, 0 -1px 0 black inset;
-webkit-box-shadow: 0 1px 0 #1a1a1a inset, 0 -1px 0 black inset;
box-shadow: 0 1px 0 #1a1a1a inset, 0 -1px 0 black inset;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3);
padding: 10px 17px;
text-align: left;
border-left: 10px solid black;
font-family: 'DIN1451W01-Mittelschrif', Arial, Helvetica, sans-serif;
font-size: 15px;
font-weight: 600;
}
.dropdown [data-toggle="dropdown"]:hover {
background: #121211;
color: white;
border-left: 10px solid #d02422;
}
.dropdown .icon-arrow {
position: absolute;
display: block;
font-size: 0.8em;
color: #fff;
top: 14px;
right: 10px;
}
.dropdown .icon-arrow.open {
-moz-transform: rotate(-180deg);
-ms-transform: rotate(-180deg);
-webkit-transform: rotate(-180deg);
transform: rotate(-180deg);
-moz-transition: -moz-transform 0.6s;
-o-transition: -o-transform 0.6s;
-webkit-transition: -webkit-transform 0.6s;
transition: transform 0.6s;
}
.dropdown .icon-arrow.close {
-moz-transform: rotate(0deg);
-ms-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
-moz-transition: -moz-transform 0.6s;
-o-transition: -o-transform 0.6s;
-webkit-transition: -webkit-transform 0.6s;
transition: transform 0.6s;
}
.dropdown .icon-arrow:before {
content: '\25BC';
}
.dropdown .dropdown-menu {
max-height: 0;
overflow: hidden;
list-style: none;
padding: 0;
margin: 0;
}
.dropdown .dropdown-menu li {
padding: 0;
}
.dropdown .dropdown-menu li a {
display: block;
color: black;
background: #EEE;
-moz-box-shadow: 0 1px 0 white inset, 0 -1px 0 #d4d4d4 inset;
-webkit-box-shadow: 0 1px 0 white inset, 0 -1px 0 #d4d4d4 inset;
box-shadow: 0 1px 0 white inset, 0 -1px 0 #d4d4d4 inset;
text-shadow: 0 -1px 0 rgba(255, 255, 255, 0.3);
padding: 10px 10px;
font-size: 13px;
text-indent: 30px;
font-family: 'DIN1451W01-Mittelschrif', Arial, Helvetica, sans-serif;
border-left: 10px solid #d02422;
font-weight: 500;
}
.dropdown .dropdown-menu li a:hover {
background: #FFFFFF;
color: #d02422;
font-weight: 700;
border-left: 10px solid black;
}
.dropdown .show,
.dropdown .hide {
-moz-transform-origin: 50% 0%;
-ms-transform-origin: 50% 0%;
-webkit-transform-origin: 50% 0%;
transform-origin: 50% 0%;
}
.dropdown .show {
display: block;
max-height: 9999px;
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
animation: showAnimation 0.5s ease-in-out;
-moz-animation: showAnimation 0.5s ease-in-out;
-webkit-animation: showAnimation 0.5s ease-in-out;
-moz-transition: max-height 1s ease-in-out;
-o-transition: max-height 1s ease-in-out;
-webkit-transition: max-height 1s ease-in-out;
transition: max-height 1s ease-in-out;
}
.dropdown .hide {
max-height: 0;
-moz-transform: scaleY(0);
-ms-transform: scaleY(0);
-webkit-transform: scaleY(0);
transform: scaleY(0);
animation: hideAnimation 0.4s ease-out;
-moz-animation: hideAnimation 0.4s ease-out;
-webkit-animation: hideAnimation 0.4s ease-out;
-moz-transition: max-height 0.6s ease-out;
-o-transition: max-height 0.6s ease-out;
-webkit-transition: max-height 0.6s ease-out;
transition: max-height 0.6s ease-out;
}
@keyframes showAnimation {
0% {
-moz-transform: scaleY(0.1);
-ms-transform: scaleY(0.1);
-webkit-transform: scaleY(0.1);
transform: scaleY(0.1);
}
40% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
100% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
}
@-moz-keyframes showAnimation {
0% {
-moz-transform: scaleY(0.1);
-ms-transform: scaleY(0.1);
-webkit-transform: scaleY(0.1);
transform: scaleY(0.1);
}
40% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
100% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
}
@-webkit-keyframes showAnimation {
0% {
-moz-transform: scaleY(0.1);
-ms-transform: scaleY(0.1);
-webkit-transform: scaleY(0.1);
transform: scaleY(0.1);
}
40% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.04);
-ms-transform: scaleY(1.04);
-webkit-transform: scaleY(1.04);
transform: scaleY(1.04);
}
100% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
}
@keyframes hideAnimation {
0% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(0);
-ms-transform: scaleY(0);
-webkit-transform: scaleY(0);
transform: scaleY(0);
}
}
@-moz-keyframes hideAnimation {
0% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(0);
-ms-transform: scaleY(0);
-webkit-transform: scaleY(0);
transform: scaleY(0);
}
}
@-webkit-keyframes hideAnimation {
0% {
-moz-transform: scaleY(1);
-ms-transform: scaleY(1);
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
60% {
-moz-transform: scaleY(0.98);
-ms-transform: scaleY(0.98);
-webkit-transform: scaleY(0.98);
transform: scaleY(0.98);
}
80% {
-moz-transform: scaleY(1.02);
-ms-transform: scaleY(1.02);
-webkit-transform: scaleY(1.02);
transform: scaleY(1.02);
}
100% {
-moz-transform: scaleY(0);
-ms-transform: scaleY(0);
-webkit-transform: scaleY(0);
transform: scaleY(0);
}
}
.whole-body {
position: relative;
max-width: 1200px;
margin: 0 auto;
}
.full-body {
position: relative;
max-width: 1200px;
margin: 5% auto;
}
.row {
width: 100%;
margin-left: 5%;
}
.col-sm-6 {
width: 30%;
float: left;
margin: 5% 0% 0 0;
}
.box-hover{
display: none;
width: 75%;
background-color: rgb(208, 36, 34);
border: 1px solid #fff;
height: 200px;
margin: 15% 0 0 15%;
padding: 5%;
}
@media screen and (max-width: 600px) {
.col-sm-6{width:80%;}
.container{width:80%;}
```
I'm also running a bootstrap script if that's any importance. Been stuck for hours, any help would be appreciated.
|
Add the CSS to your child themes style.css file or load it using wp\_enqueue\_scripts
```
add_action( 'wp_enqueue_scripts', 'wpsites_load_custom_styles' );
function wpsites_load_custom_styles() {
wp_register_style( 'custom-css', get_stylesheet_directory_uri() . '/your-style.css', false, '1.0.0' );
wp_enqueue_style( 'custom-css' );
}
```
[Source](http://wpsites.net/wordpress-themes/second-style-sheet-theme/)
|
193,904 |
<p>My company is working on a project that will have to display Events based on a the Office they are located in and the Event Leader associated with that Office. </p>
<p>What we need is to build a system that allows Events, Offices and Event Leaders to be custom post types with an inheritance between them. </p>
<p>To display them, I think it would be easiest to fill an array with the relevant post types and then loop through the array to display them. I've never heard of this being done though. Is it possible to add Custom Post Types to an array? </p>
<p>EDIT: We're looking to display post types from an array because we are only showing posts based on the proximity to a certain zip code. The thought was that we would loop through the database and pull out the relevant post types and store them in an array so that we are able to display only the relevant post types on the fly.</p>
|
[
{
"answer_id": 193896,
"author": "jpburn",
"author_id": 75868,
"author_profile": "https://wordpress.stackexchange.com/users/75868",
"pm_score": -1,
"selected": false,
"text": "<p>Please try this instead. Replace your css by : <code><link rel=\"stylesheet\" type=\"text/css\" href=\"<?php echo get_template_directory_uri(); ?>/assets/stylesheets/styles.css\" /></code> in the head section</p>\n"
},
{
"answer_id": 193911,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 1,
"selected": true,
"text": "<p>Add the CSS to your child themes style.css file or load it using wp_enqueue_scripts</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpsites_load_custom_styles' );\nfunction wpsites_load_custom_styles() {\n\n wp_register_style( 'custom-css', get_stylesheet_directory_uri() . '/your-style.css', false, '1.0.0' );\n wp_enqueue_style( 'custom-css' );\n\n}\n</code></pre>\n\n<p><a href=\"http://wpsites.net/wordpress-themes/second-style-sheet-theme/\" rel=\"nofollow\">Source</a></p>\n"
},
{
"answer_id": 193914,
"author": "Ray Flores",
"author_id": 29355,
"author_profile": "https://wordpress.stackexchange.com/users/29355",
"pm_score": -1,
"selected": false,
"text": "<p>You could add to your functions.php (in child theme) a reference to just that one page (is_page('law-practices')) and enqueue just for that one page:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'law_practice_enqueue_style' );\nfunction law_practice_enqueue_style(){\n if (is_page('law-practices')){\n wp_register_style( 'law-styles', get_template_directory_uri() . 'law-style.css', false );\n wp_enqueue_style('law-style');\n }\n\n}\n</code></pre>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75869/"
] |
My company is working on a project that will have to display Events based on a the Office they are located in and the Event Leader associated with that Office.
What we need is to build a system that allows Events, Offices and Event Leaders to be custom post types with an inheritance between them.
To display them, I think it would be easiest to fill an array with the relevant post types and then loop through the array to display them. I've never heard of this being done though. Is it possible to add Custom Post Types to an array?
EDIT: We're looking to display post types from an array because we are only showing posts based on the proximity to a certain zip code. The thought was that we would loop through the database and pull out the relevant post types and store them in an array so that we are able to display only the relevant post types on the fly.
|
Add the CSS to your child themes style.css file or load it using wp\_enqueue\_scripts
```
add_action( 'wp_enqueue_scripts', 'wpsites_load_custom_styles' );
function wpsites_load_custom_styles() {
wp_register_style( 'custom-css', get_stylesheet_directory_uri() . '/your-style.css', false, '1.0.0' );
wp_enqueue_style( 'custom-css' );
}
```
[Source](http://wpsites.net/wordpress-themes/second-style-sheet-theme/)
|
193,907 |
<p>I am trying to modify the head and foot of my WooCommerce pages. I have an <code>if</code> statement that is supposed to target the shop and cart of WooCommerce, but it isn't. If I modify the PHP after the <code>if</code> statement nothing changes. But if I modify the PHP in the <code>else</code> statement is works:</p>
<p>This doesn't work:</p>
<pre><code><?php if (function_exists('woocommerce')): ?>
<?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/CHANGE'); ?>
<?php endif ?>
<?php else: ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
</code></pre>
<p>This does work:</p>
<pre><code><?php if (function_exists('woocommerce')): ?>
<?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
<?php else: ?>
<?php get_template_part('inc/CHANGE'); ?>
<?php endif ?>
</code></pre>
<p>I think the function WooCommerce might not be properly defined, because this also works:</p>
<pre><code><?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/header-shop'); ?>
<?php else: ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
</code></pre>
|
[
{
"answer_id": 193908,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 6,
"selected": true,
"text": "<p>Your edit got me to this idea, there indeed is no function called »woocommerce«, there is a class »<code>WooCommerce</code>« though. One thing to be aware of is, that the check has to late enough, so that plug-ins are actually initialized, otherwise - obviously - the class won't exists and the check returns <code>false</code>. So your check should look like this:</p>\n\n<pre><code>if ( class_exists( 'WooCommerce' ) ) {\n // some code\n} else {\n / more code\n}\n</code></pre>\n\n<p>On the WooCommerce documentation page »<a href=\"http://docs.woothemes.com/document/create-a-plugin/\" rel=\"noreferrer\">Creating a plugin for WooCommerce</a>« I have found this:</p>\n\n<pre><code>/**\n * Check if WooCommerce is active\n **/\nif ( \n in_array( \n 'woocommerce/woocommerce.php', \n apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) \n ) \n) {\n // Put your plugin code here\n}\n</code></pre>\n\n<p>Personally I think it is not nearly as reliable as checking for the class. For obvious reasons, what if the folder/file name is different, but should work just fine too. Besides if you do it like this, then there is an API function you can use, fittingly named <a href=\"http://codex.wordpress.org./Function_Reference/is_plugin_active\" rel=\"noreferrer\"><code>is_plugin_active()</code></a>. But because it is normally only available on admin pages, you have to make it available by including <code>wp-admin/includes/plugin.php</code>, where the function resides. Using it the check would look like this:</p>\n\n<pre><code>include_once( ABSPATH . 'wp-admin/includes/plugin.php' );\nif ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {\n // some code\n} else {\n / more code\n}\n</code></pre>\n"
},
{
"answer_id": 230889,
"author": "Prem Tiwari",
"author_id": 88492,
"author_profile": "https://wordpress.stackexchange.com/users/88492",
"pm_score": 0,
"selected": false,
"text": "<p>You can wrap your plugin in a check to see if WooCommerce is installed and active or not :</p>\n\n<pre><code>if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {\necho 'WooCommerce is active.';\n} else {\necho 'WooCommerce is not Active.';\n}\n</code></pre>\n"
},
{
"answer_id": 246525,
"author": "Jan Żankowski",
"author_id": 82066,
"author_profile": "https://wordpress.stackexchange.com/users/82066",
"pm_score": 2,
"selected": false,
"text": "<p>To improve on the answers given, we're using this:</p>\n\n<pre><code>$all_plugins = apply_filters('active_plugins', get_option('active_plugins'));\nif (stripos(implode($all_plugins), 'woocommerce.php')) {\n // Put your plugin code here\n}\n</code></pre>\n\n<p>This prevents two problems:</p>\n\n<ul>\n<li>WooCommerce being installed in a non-standard directory - in which case <code>if ( in_array( 'woocommerce/woocommerce.php', apply_filters(...</code> doesn't work. </li>\n<li>This check being invoked before WooCommerce is loaded - in which case <code>if ( class_exists( 'WooCommerce' ) ) { .. }</code> doesn't work.</li>\n</ul>\n"
},
{
"answer_id": 284407,
"author": "kontur",
"author_id": 27033,
"author_profile": "https://wordpress.stackexchange.com/users/27033",
"pm_score": 3,
"selected": false,
"text": "<p>Many of the official WooCommerce plugins solve this by checking for the <code>WC_VERSION</code> constant, which WooCommerce defines, once all plugins have loaded. Simplified code:</p>\n\n<pre><code>add_action('plugins_loaded', 'check_for_woocommerce');\nfunction check_for_woocommerce() {\n if (!defined('WC_VERSION')) {\n // no woocommerce :(\n } else {\n var_dump(\"WooCommerce installed in version\", WC_VERSION);\n }\n}\n</code></pre>\n\n<p>The added bonus is that you can use PHP's <code>version_compare()</code> to further check if a new enough version of WooCommerce is installed (if you code requires specific capabilities), since the WC_VERSION constant is suitable for this.</p>\n"
},
{
"answer_id": 354382,
"author": "Nilesh",
"author_id": 179630,
"author_profile": "https://wordpress.stackexchange.com/users/179630",
"pm_score": 2,
"selected": false,
"text": "<p>I found this useful from the WooCommerce developer documentation. </p>\n\n<p>You can simply call <code>is_woocommerce_active()</code> function within your plugin file.</p>\n\n<p>Example</p>\n\n<pre><code>if ( ! is_woocommerce_active() ) \n{\n add_action( 'admin_notices', 'WC_Subscriptions::woocommerce_inactive_notice' );\n return;\n}\n</code></pre>\n\n<p><strong>is_woocommerce_active</strong> defined as below as per woo documentation</p>\n\n<pre><code>/**\n * Check if WooCommerce is activated\n */\nif ( ! function_exists( 'is_woocommerce_activated' ) ) {\n function is_woocommerce_activated() {\n if ( class_exists( 'woocommerce' ) ) { return true; } else { return false; }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 398759,
"author": "Devner",
"author_id": 12210,
"author_profile": "https://wordpress.stackexchange.com/users/12210",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Solution that I use in 2021:</strong></p>\n<pre><code>add_action( 'admin_init', 'my_plugin_check_if_woocommerce_installed' );\nfunction my_plugin_check_if_woocommerce_installed() {\n\n // If WooCommerce is NOT installed, Deactivate the plugin\n if ( is_admin() && current_user_can( 'activate_plugins') && !is_plugin_active( 'woocommerce/woocommerce.php') ) {\n\n // Show dismissible error notice\n add_action( 'admin_notices', 'my_plugin_woocommerce_check_notice' );\n\n // Deactivate this plugin\n deactivate_plugins( plugin_basename( __FILE__) );\n if ( isset( $_GET['activate'] ) ) {\n unset( $_GET['activate'] );\n }\n }\n // If WooCommerce is installed, activate the plugin and carry out further processing\n elseif ( is_admin() && is_plugin_active( 'woocommerce/woocommerce.php') ) {\n\n // Carry out further processing here\n }\n}\n\n// Show dismissible error notice if WooCommerce is not present\nfunction my_plugin_woocommerce_check_notice() {\n ?>\n <div class="alert alert-danger notice is-dismissible">\n <p>Sorry, but this plugin requires WooCommerce in order to work.\n So please ensure that WooCommerce is both installed and activated.\n </p>\n </div>\n <?php\n}\n</code></pre>\n<p>The code runs on <strong>'admin_init'</strong>, rather than on 'register_activation_hook' because it needs WooCommerce to be loaded and detected successfully. So if WooCommerce is NOT detected, it does the following:</p>\n<p>a) Shows a dismissible error notice to Admin about the absence of WooCommerce. This is very graceful as it does not use 'wp_die'.</p>\n<p>b) Deactivates your custom plugin automatically.</p>\n<p>If WooCommerce is detected, you may proceed with adding menu links, etc. as needed.</p>\n<p><em><strong>CAVEATS:</strong></em></p>\n<ol>\n<li><p>The above solution works on the assumption that the core name of WooCommerce plugin and its main file remains "woocommerce". If that were to change anytime in the future, then the checks will break. So in order to make this code work at that time, the then current WooCommerce directory name and main file name should be updated in the above code, within the <code>if</code> check and <code>elseif</code> check.</p>\n</li>\n<li><p>Do note that if both WooCommerce and your plugins are installed and running successfully, then if you were to deactivate WooCommerce anytime for any reason, then it would automatically deactivate your plugin as well.</p>\n</li>\n</ol>\n"
}
] |
2015/07/08
|
[
"https://wordpress.stackexchange.com/questions/193907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62370/"
] |
I am trying to modify the head and foot of my WooCommerce pages. I have an `if` statement that is supposed to target the shop and cart of WooCommerce, but it isn't. If I modify the PHP after the `if` statement nothing changes. But if I modify the PHP in the `else` statement is works:
This doesn't work:
```
<?php if (function_exists('woocommerce')): ?>
<?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/CHANGE'); ?>
<?php endif ?>
<?php else: ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
```
This does work:
```
<?php if (function_exists('woocommerce')): ?>
<?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
<?php else: ?>
<?php get_template_part('inc/CHANGE'); ?>
<?php endif ?>
```
I think the function WooCommerce might not be properly defined, because this also works:
```
<?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/header-shop'); ?>
<?php else: ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
```
|
Your edit got me to this idea, there indeed is no function called »woocommerce«, there is a class »`WooCommerce`« though. One thing to be aware of is, that the check has to late enough, so that plug-ins are actually initialized, otherwise - obviously - the class won't exists and the check returns `false`. So your check should look like this:
```
if ( class_exists( 'WooCommerce' ) ) {
// some code
} else {
/ more code
}
```
On the WooCommerce documentation page »[Creating a plugin for WooCommerce](http://docs.woothemes.com/document/create-a-plugin/)« I have found this:
```
/**
* Check if WooCommerce is active
**/
if (
in_array(
'woocommerce/woocommerce.php',
apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
)
) {
// Put your plugin code here
}
```
Personally I think it is not nearly as reliable as checking for the class. For obvious reasons, what if the folder/file name is different, but should work just fine too. Besides if you do it like this, then there is an API function you can use, fittingly named [`is_plugin_active()`](http://codex.wordpress.org./Function_Reference/is_plugin_active). But because it is normally only available on admin pages, you have to make it available by including `wp-admin/includes/plugin.php`, where the function resides. Using it the check would look like this:
```
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
// some code
} else {
/ more code
}
```
|
193,930 |
<p>I'm using <strong>WordPress 4.2.2</strong> and the "Contact Form 7" plugin <strong>version 4.2.1</strong>. But when my contact form shortcode outputs the html code the <code>name=""</code> attribute is blank and W3C html validator is giving me errors because of this. How can I fix this?</p>
|
[
{
"answer_id": 193932,
"author": "Shiv Singh",
"author_id": 50897,
"author_profile": "https://wordpress.stackexchange.com/users/50897",
"pm_score": 0,
"selected": false,
"text": "<p>i think you have some mistake on form creation</p>\n\n<p>it should be like</p>\n\n<pre><code>[text* text-1 class:form-control placeholder \"Name\"]\n</code></pre>\n\n<p>Where <code>text-1</code> is name attribute.</p>\n\n<p>So check your end and fix issue. </p>\n"
},
{
"answer_id": 194470,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": false,
"text": "<p><strong>UPDATE:</strong> This has been fixed in <a href=\"http://contactform7.com/2015/07/30/contact-form-7-422/\" rel=\"nofollow\">Contact Form 7 - v4.2.2</a></p>\n\n<p>The issue is that whenever Contact Form 7 generates the form shortcode it doesn't create a name attribute and it doesn't seem to fallback to using the title attribute of the shortcode. HTML 5 doesn't like empty name attributes.</p>\n\n<p>One solution until this is fixed could be to add an attribute to your Contact Form 7 shortcode <code>html_name</code> and give it some kind of string value. This will solve the validation issue. It's something WPCF7 should handle but it works in the meantime.</p>\n\n<pre><code>[contact-form-7 id=\"4\" title=\"Contact Form\" html_name=\"Contact Form 1\"]\n</code></pre>\n"
}
] |
2015/07/09
|
[
"https://wordpress.stackexchange.com/questions/193930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56854/"
] |
I'm using **WordPress 4.2.2** and the "Contact Form 7" plugin **version 4.2.1**. But when my contact form shortcode outputs the html code the `name=""` attribute is blank and W3C html validator is giving me errors because of this. How can I fix this?
|
**UPDATE:** This has been fixed in [Contact Form 7 - v4.2.2](http://contactform7.com/2015/07/30/contact-form-7-422/)
The issue is that whenever Contact Form 7 generates the form shortcode it doesn't create a name attribute and it doesn't seem to fallback to using the title attribute of the shortcode. HTML 5 doesn't like empty name attributes.
One solution until this is fixed could be to add an attribute to your Contact Form 7 shortcode `html_name` and give it some kind of string value. This will solve the validation issue. It's something WPCF7 should handle but it works in the meantime.
```
[contact-form-7 id="4" title="Contact Form" html_name="Contact Form 1"]
```
|
193,991 |
<p>I am new to ACF , so far I managed to add a new custom field and did this</p>
<p><img src="https://i.stack.imgur.com/di01x.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/yuAJc.png" alt="enter image description here"></p>
<p>Visitor can enter application no. and password to get its application statuses which admin has added.</p>
<p>I have used Repeater, it feels better working for me, Only 1 issue remaining, the get_field() is taking argument of (field name, post id) in my case I called it application_id in my above mentioned efforts. How can users search via the Application number which I will assign in integers format. So far I have done this (Ignore the inline css)</p>
<p><img src="https://i.stack.imgur.com/fTXc9.png" alt="enter image description here"></p>
<pre><code> <div class="entry-content">
<form method="post">
<label>Enter Application ID:</label>
<input type="text" name="application_id">
<label>Enter Password:</label>
<input type="password" name="application_pass">
<center style="margin: 10px 0;"><input type="submit" name="submit" value="search"></center>
</form>
<?php
$application_id = $_POST["application_id"];
$entered_pass = $_POST["application_pass"];
$client_name = get_field("client_name", $application_id);
$program = get_field("program", $application_id);
$password = get_field("password", $application_id);
$application_status = get_field("application_status", $application_id);
if ($entered_pass == $password) {
echo " <div><span style='width:40%; float:left; font-weight: bold;'>Client Name:</span> <span style='width:60%; float:left;'>{$client_name} </span></div>
<div><span style='width:40%; float:left; font-weight: bold;'>Program Applied: </span> <span style='width:60%; float:left;'> {$program} </span></div>
<div><span style='font-weight: bold;'>Application Status:</span> <hr style='margin:3px;'>" ?>
<?php $x = 1;
if(get_field('application_status', $application_id)): ?>
<ul style="list-style: outside none none; font-weight: bold;">
<li style="width: 5%; float: left;">S#</li>
<li style="width: 78%; float: left;">Description</li>
<li style="width: 17%; float: left;">Date</li>
</ul>
<hr style='margin:3px;'>
<?php while(the_repeater_field('application_status', $application_id)): ?>
<ul style="list-style: outside none none;">
<li style="width: 5%; float: left;"><?php echo $x; $x++; ?></li>
<li style="width: 78%; float: left;"><?php the_sub_field('last_update'); ?></li>
<li style="width: 17%; float: left;"><?php the_sub_field('update_date'); ?></li>
</ul>
<?php endwhile; ?>
<?php
endif;
?>
<?php "</div>";} ?><!-- entered pass if -->
</div><!-- .entry-content -->
</code></pre>
|
[
{
"answer_id": 193952,
"author": "Shuvo Habib",
"author_id": 64429,
"author_profile": "https://wordpress.stackexchange.com/users/64429",
"pm_score": 0,
"selected": false,
"text": "<p>One of the easiest way you need to do is install and activate the <a href=\"http://wordpress.org/plugins/duplicator/\" rel=\"nofollow\">Duplicator plugin</a> on your live site. Duplicator plugin allows you to create duplicate package of your entire WordPress site. It can be used to move your WordPress site to a new location, and can also be used as a backup plugin.</p>\n"
},
{
"answer_id": 193956,
"author": "Anand",
"author_id": 73187,
"author_profile": "https://wordpress.stackexchange.com/users/73187",
"pm_score": 1,
"selected": false,
"text": "<p>this are the steps you need to care when you setup wordpress locally from server.</p>\n\n<ol>\n<li><p>Download wordpress folder and database.(keep back up) </p></li>\n<li><p>setup db and change on wp_option table for \"home_url\" and \"site_url\".</p></li>\n<li><p>change permalink and and reset .htaccess. </p></li>\n<li><p>change on custom menu link which you have added</p></li>\n<li><p>restart it.</p></li>\n</ol>\n"
}
] |
2015/07/09
|
[
"https://wordpress.stackexchange.com/questions/193991",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48184/"
] |
I am new to ACF , so far I managed to add a new custom field and did this


Visitor can enter application no. and password to get its application statuses which admin has added.
I have used Repeater, it feels better working for me, Only 1 issue remaining, the get\_field() is taking argument of (field name, post id) in my case I called it application\_id in my above mentioned efforts. How can users search via the Application number which I will assign in integers format. So far I have done this (Ignore the inline css)

```
<div class="entry-content">
<form method="post">
<label>Enter Application ID:</label>
<input type="text" name="application_id">
<label>Enter Password:</label>
<input type="password" name="application_pass">
<center style="margin: 10px 0;"><input type="submit" name="submit" value="search"></center>
</form>
<?php
$application_id = $_POST["application_id"];
$entered_pass = $_POST["application_pass"];
$client_name = get_field("client_name", $application_id);
$program = get_field("program", $application_id);
$password = get_field("password", $application_id);
$application_status = get_field("application_status", $application_id);
if ($entered_pass == $password) {
echo " <div><span style='width:40%; float:left; font-weight: bold;'>Client Name:</span> <span style='width:60%; float:left;'>{$client_name} </span></div>
<div><span style='width:40%; float:left; font-weight: bold;'>Program Applied: </span> <span style='width:60%; float:left;'> {$program} </span></div>
<div><span style='font-weight: bold;'>Application Status:</span> <hr style='margin:3px;'>" ?>
<?php $x = 1;
if(get_field('application_status', $application_id)): ?>
<ul style="list-style: outside none none; font-weight: bold;">
<li style="width: 5%; float: left;">S#</li>
<li style="width: 78%; float: left;">Description</li>
<li style="width: 17%; float: left;">Date</li>
</ul>
<hr style='margin:3px;'>
<?php while(the_repeater_field('application_status', $application_id)): ?>
<ul style="list-style: outside none none;">
<li style="width: 5%; float: left;"><?php echo $x; $x++; ?></li>
<li style="width: 78%; float: left;"><?php the_sub_field('last_update'); ?></li>
<li style="width: 17%; float: left;"><?php the_sub_field('update_date'); ?></li>
</ul>
<?php endwhile; ?>
<?php
endif;
?>
<?php "</div>";} ?><!-- entered pass if -->
</div><!-- .entry-content -->
```
|
this are the steps you need to care when you setup wordpress locally from server.
1. Download wordpress folder and database.(keep back up)
2. setup db and change on wp\_option table for "home\_url" and "site\_url".
3. change permalink and and reset .htaccess.
4. change on custom menu link which you have added
5. restart it.
|
194,010 |
<p>I am doing a <code>WP_Query</code> trying to filter out the posts by Metadata. </p>
<pre><code> $args = array(
'ignore_sticky_posts'=> 1,
'post_type' => 'post_projects',
'post_status' => 'publish',
'posts_per_page' => $nr_posts,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'wpl_goal_amount',
'value' => 100,
'compare' => '!=',
),
array(
'key' => 'wpl_location',
'value' => 'Europe',
'compare' => '=',
),
),
);
</code></pre>
<p>I am testing this out with two posts. One of them has "Europe" in it's array of locations, but whenever I run this, it doesn't come up with anything.</p>
<p>QUESTION UPDATE:</p>
<p>I am using Option Tree to save the Meta-data, and as mentioned in a previous answer, it stores serialized the post meta-data (by Wordpress' default), and in combination with that and another post, I found that there are two ways to query the serialized data. The first is more convenient, but more of a jerry-rig, and the second is more proper, but difficult:</p>
<ol>
<li><p>The easier:</p>
<pre><code> array(
'key' => 'wpl_location',
'value' => '"' . $my_value . '"',
'compare' => 'LIKE'
),
</code></pre></li>
<li><p>Compared to the better but more difficult:</p>
<pre><code> array(
'key' => 'wpl_location',
'value' => serialize(array(3 => 'Europe')),
'compare' => 'LIKE'
),
</code></pre></li>
</ol>
<p>I believe the second method would require me to have a (near) identical serialized array as the database, which would not work in the long-term for the system that I am creating, because it will need to match one out of many items in the array.</p>
<p>My updated question:</p>
<p>Should I continue down this path and use the first method, or do I need to dump Option Tree and figure out a way to add the meta-data to the posts in unserialized form so that it can be queried?</p>
|
[
{
"answer_id": 193952,
"author": "Shuvo Habib",
"author_id": 64429,
"author_profile": "https://wordpress.stackexchange.com/users/64429",
"pm_score": 0,
"selected": false,
"text": "<p>One of the easiest way you need to do is install and activate the <a href=\"http://wordpress.org/plugins/duplicator/\" rel=\"nofollow\">Duplicator plugin</a> on your live site. Duplicator plugin allows you to create duplicate package of your entire WordPress site. It can be used to move your WordPress site to a new location, and can also be used as a backup plugin.</p>\n"
},
{
"answer_id": 193956,
"author": "Anand",
"author_id": 73187,
"author_profile": "https://wordpress.stackexchange.com/users/73187",
"pm_score": 1,
"selected": false,
"text": "<p>this are the steps you need to care when you setup wordpress locally from server.</p>\n\n<ol>\n<li><p>Download wordpress folder and database.(keep back up) </p></li>\n<li><p>setup db and change on wp_option table for \"home_url\" and \"site_url\".</p></li>\n<li><p>change permalink and and reset .htaccess. </p></li>\n<li><p>change on custom menu link which you have added</p></li>\n<li><p>restart it.</p></li>\n</ol>\n"
}
] |
2015/07/09
|
[
"https://wordpress.stackexchange.com/questions/194010",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73346/"
] |
I am doing a `WP_Query` trying to filter out the posts by Metadata.
```
$args = array(
'ignore_sticky_posts'=> 1,
'post_type' => 'post_projects',
'post_status' => 'publish',
'posts_per_page' => $nr_posts,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'wpl_goal_amount',
'value' => 100,
'compare' => '!=',
),
array(
'key' => 'wpl_location',
'value' => 'Europe',
'compare' => '=',
),
),
);
```
I am testing this out with two posts. One of them has "Europe" in it's array of locations, but whenever I run this, it doesn't come up with anything.
QUESTION UPDATE:
I am using Option Tree to save the Meta-data, and as mentioned in a previous answer, it stores serialized the post meta-data (by Wordpress' default), and in combination with that and another post, I found that there are two ways to query the serialized data. The first is more convenient, but more of a jerry-rig, and the second is more proper, but difficult:
1. The easier:
```
array(
'key' => 'wpl_location',
'value' => '"' . $my_value . '"',
'compare' => 'LIKE'
),
```
2. Compared to the better but more difficult:
```
array(
'key' => 'wpl_location',
'value' => serialize(array(3 => 'Europe')),
'compare' => 'LIKE'
),
```
I believe the second method would require me to have a (near) identical serialized array as the database, which would not work in the long-term for the system that I am creating, because it will need to match one out of many items in the array.
My updated question:
Should I continue down this path and use the first method, or do I need to dump Option Tree and figure out a way to add the meta-data to the posts in unserialized form so that it can be queried?
|
this are the steps you need to care when you setup wordpress locally from server.
1. Download wordpress folder and database.(keep back up)
2. setup db and change on wp\_option table for "home\_url" and "site\_url".
3. change permalink and and reset .htaccess.
4. change on custom menu link which you have added
5. restart it.
|
194,024 |
<p>I'm trying to list out all the child pages of a custom page I've made.</p>
<p>In my custom page, I'm doing this to list out the pages:</p>
<pre><code><?php get_header(); ?>
<?php
$subpages = new WP_Query( array(
'post_type' => 'page',
'post_parent' => $post->ID,
'posts_per_page' => -1,
'orderby' => 'menu_order'
));
if ($subpages->have_posts()) : while ($subpages->have_posts()) : the_post(); ?>
...
<?php endwhile; else : ?>
...
<?php endif; ?>
<?php get_footer(); ?>
</code></pre>
<p>But this isn't working. Now it only lists out itself (the parent, which I don't want listed out at all), and none of its children.</p>
<p>Also, the sites just keeps loading, while everything except the footer is displayed. It's like its returning one half of the page, and then hangs as it works on the rest. While running this my CPU and fan suddenly kicks in.</p>
<p>Does anyone know why?</p>
|
[
{
"answer_id": 194025,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": true,
"text": "<p>I tested the query and it does work so the only thing I can spot that is misleading but not right is directly after you <code>while()</code> statement you have <code>the_post()</code>. This doesn't work in secondary queries, it should look like:</p>\n\n<pre><code><?php if( $subpages->have_posts() ) : ?>\n\n <?php while( $subpages->have_posts() ) : $subpages->the_post(); ?>\n\n ...\n\n <?php endwhile; ?>\n\n<?php endif; ?>\n</code></pre>\n\n<p>Note the <code>$subpages->the_post();</code> - since it's a secondary query we need to continue referencing the query variable. After this all the normal loop functions work as expected, such as: <code>the_title()</code>, <code>the_content()</code>, etc.</p>\n"
},
{
"answer_id": 225459,
"author": "Andrey",
"author_id": 93399,
"author_profile": "https://wordpress.stackexchange.com/users/93399",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php \nglobal $post;\n$child_pages_query_args = array(\n 'post_type' => 'page',\n 'post_parent' => '93',\n 'orderby' => 'date DESC'\n);\n$child_pages = new WP_Query( $child_pages_query_args );\n?>\n\n<?php if ( $child_pages->have_posts() ) : while ( $child_pages->have_posts() ) : $child_pages->the_post(); ?>\n\n<div class=\"col-lg-6\">\n<div class=\"featured-pwrap\"> \n <?php if ( has_post_thumbnail() ) { the_post_thumbnail('home-pages-thumb'); } else { ?>\n <img class=\"attachment-home-pages-thumb\" src=\"<?php bloginfo('template_directory'); ?>/images/default-image.jpg\" alt=\"<?php the_title(); ?>\" />\n <?php } ?>\n<h3><?php the_title(); ?></h3>\n<a href=\"<?php the_permalink(); ?>\" class=\"futured-more\">Read more</a>\n</div>\n</div>\n<?php endwhile; endif; wp_reset_postdata(); ?>\n</code></pre>\n"
}
] |
2015/07/09
|
[
"https://wordpress.stackexchange.com/questions/194024",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43933/"
] |
I'm trying to list out all the child pages of a custom page I've made.
In my custom page, I'm doing this to list out the pages:
```
<?php get_header(); ?>
<?php
$subpages = new WP_Query( array(
'post_type' => 'page',
'post_parent' => $post->ID,
'posts_per_page' => -1,
'orderby' => 'menu_order'
));
if ($subpages->have_posts()) : while ($subpages->have_posts()) : the_post(); ?>
...
<?php endwhile; else : ?>
...
<?php endif; ?>
<?php get_footer(); ?>
```
But this isn't working. Now it only lists out itself (the parent, which I don't want listed out at all), and none of its children.
Also, the sites just keeps loading, while everything except the footer is displayed. It's like its returning one half of the page, and then hangs as it works on the rest. While running this my CPU and fan suddenly kicks in.
Does anyone know why?
|
I tested the query and it does work so the only thing I can spot that is misleading but not right is directly after you `while()` statement you have `the_post()`. This doesn't work in secondary queries, it should look like:
```
<?php if( $subpages->have_posts() ) : ?>
<?php while( $subpages->have_posts() ) : $subpages->the_post(); ?>
...
<?php endwhile; ?>
<?php endif; ?>
```
Note the `$subpages->the_post();` - since it's a secondary query we need to continue referencing the query variable. After this all the normal loop functions work as expected, such as: `the_title()`, `the_content()`, etc.
|
194,028 |
<p>I am trying to run some custom jquery function every time the colorpicker's color change. The colorpicker is include as part of the WP core. I have been looking at the JS code, but I can't figure out what's the trigger that updates the color.</p>
<p>I have tried listening for several classes, and also listening for changes on the text input (the one that holds the color hex value), but no luck.</p>
<p>Has anyone done this before?</p>
|
[
{
"answer_id": 194034,
"author": "gdaniel",
"author_id": 30984,
"author_profile": "https://wordpress.stackexchange.com/users/30984",
"pm_score": 3,
"selected": false,
"text": "<p>I hate answering my own question, but hopefully this can help someone else with similar issues:</p>\n\n<p>Wordpress uses Iris color picker.\n<a href=\"http://automattic.github.io/Iris/#\">http://automattic.github.io/Iris/#</a></p>\n\n<p>Wordpress also creates a jquery widget with default settings for Iris.\nThe file can be found under wp-admin/js/color-picker.js</p>\n\n<p>At first I was trying to pass values directly to iris(), which works, but that overrides the wordpress widget.</p>\n\n<p>Once I found out about the widget, I wrote the following:</p>\n\n<pre><code>$(\".wp-color-picker\").wpColorPicker(\n 'option',\n 'change',\n function(event, ui) {\n //do something on color change here\n }\n);\n</code></pre>\n\n<p>The wpColirPicker accepts a custom function for the change event. So it runs first the default actions and then it allows you to add your own.</p>\n"
},
{
"answer_id": 247026,
"author": "kapai1890",
"author_id": 107509,
"author_profile": "https://wordpress.stackexchange.com/users/107509",
"pm_score": 1,
"selected": false,
"text": "<p>As <strong>gdaniel</strong> was saying in his answer, WordPress uses <a href=\"http://automattic.github.io/Iris/\" rel=\"nofollow noreferrer\">Iris</a> color picker. You can pass your callbacks to wpColorPicker plugin using <strong>change</strong> and <strong>clear</strong> options. Please note that change-callback will handle all the changes except for cleaning of the field via \"Clear\" button. So use clear-callback for that purposes.</p>\n\n<pre><code>jQuery('.wp-color-picker').wpColorPicker({\n /**\n * @param {Event} event - standard jQuery event, produced by whichever\n * control was changed.\n * @param {Object} ui - standard jQuery UI object, with a color member\n * containing a Color.js object.\n */\n change: function (event, ui) {\n var element = event.target;\n var color = ui.color.toString();\n\n // Add your code here\n },\n\n /**\n * @param {Event} event - standard jQuery event, produced by \"Clear\"\n * button.\n */\n clear: function (event) {\n var element = jQuery(event.target).siblings('.wp-color-picker')[0];\n var color = '';\n\n if (element) {\n // Add your code here\n }\n }\n});\n</code></pre>\n\n<p>Please also note that if you use <em>element.value</em> in your change-callback then you'll get the old value instead of new one.</p>\n"
}
] |
2015/07/09
|
[
"https://wordpress.stackexchange.com/questions/194028",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30984/"
] |
I am trying to run some custom jquery function every time the colorpicker's color change. The colorpicker is include as part of the WP core. I have been looking at the JS code, but I can't figure out what's the trigger that updates the color.
I have tried listening for several classes, and also listening for changes on the text input (the one that holds the color hex value), but no luck.
Has anyone done this before?
|
I hate answering my own question, but hopefully this can help someone else with similar issues:
Wordpress uses Iris color picker.
<http://automattic.github.io/Iris/#>
Wordpress also creates a jquery widget with default settings for Iris.
The file can be found under wp-admin/js/color-picker.js
At first I was trying to pass values directly to iris(), which works, but that overrides the wordpress widget.
Once I found out about the widget, I wrote the following:
```
$(".wp-color-picker").wpColorPicker(
'option',
'change',
function(event, ui) {
//do something on color change here
}
);
```
The wpColirPicker accepts a custom function for the change event. So it runs first the default actions and then it allows you to add your own.
|
194,064 |
<p>I'm using Godaddy Hosting, PHP 5, and Wordpress 4.2.1</p>
<p>I have 34,000 + posts that need outdated href tags removed. I am able to remove tags, one post at a time, by using this code in a page template and changing the post_id manually. Thank you @ialocin for the wp-kses addition. The wp_postmeta table has 347,602 rows but only 34,788 have the "simple_fields" row.</p>
<p></p>
<pre><code><?php $allowed_html = array(
'p' => array(),
'img' => array(
'alt' => true,
'align' => true,
'border' => true,
'height' => true,
'hspace' => true,
'longdesc' => true,
'vspace' => true,
'src' => true,
'usemap' => true,
'width' => true,
),
'br' => array()
);
?>
<?php $source = get_post_meta(24532, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', true); ?>
<?php update_post_meta(24532, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', wp_kses ($source, $allowed_html) ); ?>
</code></pre>
<p></p>
<p>However, I need to apply this to many thousands of wp_postmeta rows. After modifying <a href="https://wordpress.stackexchange.com/a/189374/75960">this example</a> from @TheDeadMedic, I was able to throw an error with the following code, but so far it does nothing to the database. </p>
<p>The error is: </p>
<blockquote>
<p>Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 32 bytes) in .../wp-includes/wp-db.php on line 2204 </p>
</blockquote>
<p>If I change the posts_per_page to -1, it does not appear to do anything. It just refreshes the page.</p>
<pre><code><?php
/**
* Update All postmeta
*
*/
$args = array(
'fields' => 'ids', // MAGIC! Just get an array of id's, no objects committed to memory
'posts_per_page' => 500, // Batch size: look at all posts
'post_type' => 'post',
'date_query' => array( // Make sure the post is over 30 days old
array(
'column' => 'post_date_gmt',
'before' => '1 month ago'
)
),
);
$query = new WP_Query;
$paged = 1;
$count = 0;
$total = null;
do {
$args['no_found_rows'] = isset( $total ); // No need to SQL_CALC_FOUND_ROWS on subsequent iterations
$args['paged'] = $paged++;
$post_ids = $query->query( $args );
update_postmeta_cache( $post_ids ); // Get all meta for this group of posts
if ( ! isset( $total ) )
$total = $query->found_posts;
$count += $query->post_count;
foreach ( $post_ids as $post_id ) {
$allowed_html = array( // Declare tags not to be removed
'p' => array(),
'img' => array(
'alt' => true,
'align' => true,
'border' => true,
'height' => true,
'hspace' => true,
'longdesc' => true,
'vspace' => true,
'src' => true,
'usemap' => true,
'width' => true,
),
'br' => array()
);
$source = get_post_meta($post_id, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', true);
update_post_meta($$post_id, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', wp_kses ($source, $allowed_html) );
}
} while ( $count < $total );
?>
</code></pre>
<p>Can anyone see what is off or missing? Does the 'fields' => 'ids', // MAGIC! from @TheDeadMedic need to be "post_id" or does this need to be a foreach instead of while or other?</p>
<p>What is the best way to do this automatically, dynamically, procedurally, else wise or other?</p>
<p>Any solutions, leads, clues or hints are greatly appreciated.</p>
|
[
{
"answer_id": 194073,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>Firstly, I would consider using one of WordPress' <a href=\"http://codex.wordpress.org/Data_Validation#HTML.2FXML\" rel=\"nofollow noreferrer\"><code>wp_kses</code>-like</a> functions, instead of PHP's <code>strip_tags()</code>.</p>\n\n<p>Secondly, query your posts with <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> or <a href=\"https://codex.wordpress.org/Function_Reference/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> with the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter\" rel=\"nofollow noreferrer\"><code>fields</code> parameter</a> set to <code>ids</code> - seems like you don't need more than that.</p>\n\n<p>Thirdly, split up your loop into steps that are effective and manageable. Because 34000+ posts will likely reach the limits of your server - at the very least regarding processing time. </p>\n\n<p>You could for example make smart use of the <code>posts_per_page</code> and/or <code>offset</code> parameters for <code>WP_Query</code>/<code>get_posts</code>. Or you might do it by handling the complete array of IDs you can get by setting <code>posts_per_page</code> to <code>-1</code> another way with PHP. For an exemplary approach take a look at the following <a href=\"https://wordpress.stackexchange.com/a/189374/22534\">answer by @TheDeadMedic</a> on a similar matter.</p>\n"
},
{
"answer_id": 194074,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 1,
"selected": false,
"text": "<p>The quickest solution is export posts table from database, replace tags this using any code-editor. For posts content are simple text not serialized, in this way you can do all replacement in less than 10 minutes without any hassle. Then import the sql file in db.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 194075,
"author": "performadigital",
"author_id": 63100,
"author_profile": "https://wordpress.stackexchange.com/users/63100",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way to do this would be via SQL.\nFirstly take a backup of your database in case anything goes wrong.\nThen using phpMyAdmin or a similar SQL frontend run this SQL command:</p>\n\n<pre><code>UPDATE wp_posts SET post_content = REPLACE(post_content, '<br>', '');\n</code></pre>\n\n<p>This will replace the tag </p>\n\n<pre><code><br>\n</code></pre>\n\n<p>with nothing in all post content.</p>\n\n<p>If the tags are in post meta and not post content then it's a little more work as you'll need to go into your database and find which meta key the tags are in.</p>\n\n<p>Look into your wp__postmeta table and look for the field you've listed above in the meta_key column then you can run this SQL query:</p>\n\n<pre><code>UPDATE wp_postmeta WHERE meta_key = 'YourMetaKey' SET meta_value = REPLACE(meta_value, '<br>', '');\n</code></pre>\n\n<p>Run these commands for each tag you want to remove from post content or post meta.</p>\n"
},
{
"answer_id": 194964,
"author": "Lawrence1972",
"author_id": 75960,
"author_profile": "https://wordpress.stackexchange.com/users/75960",
"pm_score": 2,
"selected": true,
"text": "<p>Finally, I was able to iterate through all 34,788 entries, but only by running the job in smaller batches based on the post date. Here is the final code that I used on a page template. Thank you @ialocin for setting me on the right path. The job is done, but there has to be a better, more automatic, way to iterate through the posts without setting post date or blowing out the memory. If you have a better way, please post it here. </p>\n\n<pre><code> <?php \n /**\n * Remove href tags from postmeta by post date\n *\n */\n $args = array(\n 'post_type' => 'post',\n 'fields' => 'ids',\n 'posts_per_page' => -1, // Grab all Post IDs\n 'date_query' => array( // Set the date range of the posts you want effected\n array(\n 'after' => 'June 1st, 2010',\n 'before' => array(\n 'year' => 2012,\n 'month' => 12,\n 'day' => 30,\n ),\n 'inclusive' => true,\n ),\n ),\n );\n $query = new WP_Query($args);\n if ($query->have_posts()):\n foreach( $query->posts as $id ):\n $allowed_html = array( // Declare tags not to be removed\n 'p' => array(),\n 'img' => array(\n 'alt' => true,\n 'align' => true,\n 'border' => true,\n 'height' => true,\n 'hspace' => true,\n 'longdesc' => true,\n 'vspace' => true,\n 'src' => true,\n 'usemap' => true,\n 'width' => true,\n ),\n 'br' => array()\n ); \n // retrieve the postmeta for the specific custom field, only if it has data.\n $source = get_post_meta($id,'_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', true);\n // write it back, but remove the tags with wp_kses\n update_post_meta($id, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', wp_kses ($source, $allowed_html) );\n // Wipe this post's meta from memory\n wp_cache_delete($id, 'post_meta' );\n endforeach;\n endif;\n ?>\n</code></pre>\n"
}
] |
2015/07/10
|
[
"https://wordpress.stackexchange.com/questions/194064",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75960/"
] |
I'm using Godaddy Hosting, PHP 5, and Wordpress 4.2.1
I have 34,000 + posts that need outdated href tags removed. I am able to remove tags, one post at a time, by using this code in a page template and changing the post\_id manually. Thank you @ialocin for the wp-kses addition. The wp\_postmeta table has 347,602 rows but only 34,788 have the "simple\_fields" row.
```
<?php $allowed_html = array(
'p' => array(),
'img' => array(
'alt' => true,
'align' => true,
'border' => true,
'height' => true,
'hspace' => true,
'longdesc' => true,
'vspace' => true,
'src' => true,
'usemap' => true,
'width' => true,
),
'br' => array()
);
?>
<?php $source = get_post_meta(24532, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', true); ?>
<?php update_post_meta(24532, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', wp_kses ($source, $allowed_html) ); ?>
```
However, I need to apply this to many thousands of wp\_postmeta rows. After modifying [this example](https://wordpress.stackexchange.com/a/189374/75960) from @TheDeadMedic, I was able to throw an error with the following code, but so far it does nothing to the database.
The error is:
>
> Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 32 bytes) in .../wp-includes/wp-db.php on line 2204
>
>
>
If I change the posts\_per\_page to -1, it does not appear to do anything. It just refreshes the page.
```
<?php
/**
* Update All postmeta
*
*/
$args = array(
'fields' => 'ids', // MAGIC! Just get an array of id's, no objects committed to memory
'posts_per_page' => 500, // Batch size: look at all posts
'post_type' => 'post',
'date_query' => array( // Make sure the post is over 30 days old
array(
'column' => 'post_date_gmt',
'before' => '1 month ago'
)
),
);
$query = new WP_Query;
$paged = 1;
$count = 0;
$total = null;
do {
$args['no_found_rows'] = isset( $total ); // No need to SQL_CALC_FOUND_ROWS on subsequent iterations
$args['paged'] = $paged++;
$post_ids = $query->query( $args );
update_postmeta_cache( $post_ids ); // Get all meta for this group of posts
if ( ! isset( $total ) )
$total = $query->found_posts;
$count += $query->post_count;
foreach ( $post_ids as $post_id ) {
$allowed_html = array( // Declare tags not to be removed
'p' => array(),
'img' => array(
'alt' => true,
'align' => true,
'border' => true,
'height' => true,
'hspace' => true,
'longdesc' => true,
'vspace' => true,
'src' => true,
'usemap' => true,
'width' => true,
),
'br' => array()
);
$source = get_post_meta($post_id, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', true);
update_post_meta($$post_id, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', wp_kses ($source, $allowed_html) );
}
} while ( $count < $total );
?>
```
Can anyone see what is off or missing? Does the 'fields' => 'ids', // MAGIC! from @TheDeadMedic need to be "post\_id" or does this need to be a foreach instead of while or other?
What is the best way to do this automatically, dynamically, procedurally, else wise or other?
Any solutions, leads, clues or hints are greatly appreciated.
|
Finally, I was able to iterate through all 34,788 entries, but only by running the job in smaller batches based on the post date. Here is the final code that I used on a page template. Thank you @ialocin for setting me on the right path. The job is done, but there has to be a better, more automatic, way to iterate through the posts without setting post date or blowing out the memory. If you have a better way, please post it here.
```
<?php
/**
* Remove href tags from postmeta by post date
*
*/
$args = array(
'post_type' => 'post',
'fields' => 'ids',
'posts_per_page' => -1, // Grab all Post IDs
'date_query' => array( // Set the date range of the posts you want effected
array(
'after' => 'June 1st, 2010',
'before' => array(
'year' => 2012,
'month' => 12,
'day' => 30,
),
'inclusive' => true,
),
),
);
$query = new WP_Query($args);
if ($query->have_posts()):
foreach( $query->posts as $id ):
$allowed_html = array( // Declare tags not to be removed
'p' => array(),
'img' => array(
'alt' => true,
'align' => true,
'border' => true,
'height' => true,
'hspace' => true,
'longdesc' => true,
'vspace' => true,
'src' => true,
'usemap' => true,
'width' => true,
),
'br' => array()
);
// retrieve the postmeta for the specific custom field, only if it has data.
$source = get_post_meta($id,'_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', true);
// write it back, but remove the tags with wp_kses
update_post_meta($id, '_simple_fields_fieldGroupID_1_fieldID_1_numInSet_0', wp_kses ($source, $allowed_html) );
// Wipe this post's meta from memory
wp_cache_delete($id, 'post_meta' );
endforeach;
endif;
?>
```
|
194,090 |
<p>After the <a href="http://docs.woothemes.com/document/importing-woocommerce-dummy-data/" rel="noreferrer">Woocommerce dummy products</a> are imported, I notice that in the database, there are different records in different tables but point to THE SAME photo attachment.</p>
<p>The question is why? What are the differences between those records? Is that a duplication/redundancy in data storing?</p>
<p>Let's take <code>post_id=16</code> as below snapshot. We would see as below.</p>
<ol>
<li>In table <code>wp_posts</code>, the id=16 post has <code>post_type</code>=attachment and its <code>guid</code> points to <code>T1_front_1.jpg</code> image.</li>
</ol>
<p><img src="https://i.stack.imgur.com/h3idQ.png" alt="enter image description here"></p>
<ol start="2">
<li>In table <code>wp_postmeta</code>, the one with post_id=16 is also taking the <code>meta_key</code> as <code>_wp_attachment_file</code> and <code>meta_value</code> points to <strong>the same image</strong> <code>T1_front_1.jpg</code>.</li>
</ol>
<p><img src="https://i.stack.imgur.com/Nkoca.png" alt="enter image description here"></p>
|
[
{
"answer_id": 194092,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 1,
"selected": false,
"text": "<p>First is showing the attachment file path, second is file attributes size, type, height, width etc.</p>\n\n<p>Thanks</p>\n\n<p>attachment in wp_post shows the attachment basic details title, time, author etc. </p>\n\n<p>wp_postmeta shows attachment all other details for example attachment would be text, pdf, image etc so it having different meta data for different types of posts.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 194119,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": false,
"text": "<h1>An attachment <em>is</em> a Post</h1>\n\n<p>The posts table contains information on the attachment <em>post</em>.</p>\n\n<p>In WordPress every uploaded media has it's own post entry, where <code>post_type</code> is <code>'attachment'</code> and <code>post_status</code> is <code>'inherit'</code>.</p>\n\n<p>In fact, you can get attachment post types using functions used to get other post types, like post, page or any CPT.</p>\n\n<p>That includes <code>WP_Query</code>, <code>get_posts()</code> and <code>get_post()</code>.</p>\n\n<h2>What's in <code>posts</code> table</h2>\n\n<p>For every attachment post</p>\n\n<ul>\n<li><code>post_title</code> column is used for attachment <em>title</em></li>\n<li><code>post_excerpt</code> is used for attachment <em>caption</em></li>\n<li><code>post_content</code> is used for attachment <em>description</em></li>\n</ul>\n\n<p>Note that attachment post type may have a <code>post_parent</code> that points to the ID of the post where the attachment was uploaded from.</p>\n\n<p>For example:</p>\n\n<pre><code>get_posts( 'post_type=attachment&post_parent=10' );\n</code></pre>\n\n<p>Retrieve all the post objects for attachments loaded from the edit page of the post with ID <code>10</code>;</p>\n\n<h1>An attachment is <em>not only</em> a Post</h1>\n\n<p>However, there is information for media (especially images) that simply doesn't fit the posts table.</p>\n\n<p>All this information is stored in the postmeta table, where the <code>post_id</code> column refers to the attachment row in the posts table.</p>\n\n<h2>What's in <code>postmeta</code> table</h2>\n\n<p>For example, the <code>\"alt\"</code> attribute is stored in a meta field that has the key <strong><code>'_wp_attachment_image_alt'</code></strong>.</p>\n\n<p>The meta field with key <strong><code>'_wp_attached_file'</code></strong> contains the relative path (to content folder) of the uploaded file.</p>\n\n<p>That is used to build the attachment URL and path, in functions like <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_url/\" rel=\"noreferrer\"><code>wp_get_attachment_url()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"noreferrer\"><code>wp_get_attachment_image_src()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/get_attached_file/\" rel=\"noreferrer\"><code>get_attached_file()</code></a> and so on.</p>\n\n<p>Finally, the field <code>'_wp_attachment_metadata'</code> contains different information (in a serialized array in the database):</p>\n\n<ul>\n<li>The image size (under keys <code>'width'</code> and <code>'height'</code>)</li>\n<li>Information about <strong>intermediate sizes</strong></li>\n</ul>\n\n<h2>Intermediate sizes</h2>\n\n<p>In fact, every time an image is uploaded, WordPress creates different copies of the image in different sizes.</p>\n\n<p>Please read <strong><a href=\"https://wordpress.stackexchange.com/questions/108572/set-post-thumbnail-size-vs-add-image-size/108583#108583\">this answer</a></strong> for more details.</p>\n\n<p>The key <code>\"sizes\"</code> in the <code>'_wp_attachment_metadata'</code> field contain an array with information on all generated images: the file created, the size (width and height) and so on.</p>\n\n<p>Note that the preferred way to get information from <code>'_wp_attachment_metadata'</code> is not using the <em>common</em> <code>get_post_meta()</code> but the specific <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"noreferrer\"><code>wp_get_attachment_metadata()</code></a>, as it triggers a filter.</p>\n\n<p>If you are interested in the information about a specific generated image, the function <a href=\"https://developer.wordpress.org/reference/functions/image_get_intermediate_size/\" rel=\"noreferrer\"><code>image_get_intermediate_size()</code></a> will be handy.</p>\n\n<h2>Use specific functions</h2>\n\n<p>Generally speaking, if you need information on an attachment, use the specific functions and avoid pulling data from the database; it is harder and does not triggers hooks, possibly breaking core, theme and plugins compatibility.</p>\n\n<p>There are <em>a lot</em> of functions in WordPress to work with attachments, <a href=\"https://developer.wordpress.org/?s=attachment&post_type[]=wp-parser-function\" rel=\"noreferrer\">this</a> should give you an idea...</p>\n\n<p>However, main functions are all listed in this answer.</p>\n"
}
] |
2015/07/10
|
[
"https://wordpress.stackexchange.com/questions/194090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/992/"
] |
After the [Woocommerce dummy products](http://docs.woothemes.com/document/importing-woocommerce-dummy-data/) are imported, I notice that in the database, there are different records in different tables but point to THE SAME photo attachment.
The question is why? What are the differences between those records? Is that a duplication/redundancy in data storing?
Let's take `post_id=16` as below snapshot. We would see as below.
1. In table `wp_posts`, the id=16 post has `post_type`=attachment and its `guid` points to `T1_front_1.jpg` image.

2. In table `wp_postmeta`, the one with post\_id=16 is also taking the `meta_key` as `_wp_attachment_file` and `meta_value` points to **the same image** `T1_front_1.jpg`.

|
An attachment *is* a Post
=========================
The posts table contains information on the attachment *post*.
In WordPress every uploaded media has it's own post entry, where `post_type` is `'attachment'` and `post_status` is `'inherit'`.
In fact, you can get attachment post types using functions used to get other post types, like post, page or any CPT.
That includes `WP_Query`, `get_posts()` and `get_post()`.
What's in `posts` table
-----------------------
For every attachment post
* `post_title` column is used for attachment *title*
* `post_excerpt` is used for attachment *caption*
* `post_content` is used for attachment *description*
Note that attachment post type may have a `post_parent` that points to the ID of the post where the attachment was uploaded from.
For example:
```
get_posts( 'post_type=attachment&post_parent=10' );
```
Retrieve all the post objects for attachments loaded from the edit page of the post with ID `10`;
An attachment is *not only* a Post
==================================
However, there is information for media (especially images) that simply doesn't fit the posts table.
All this information is stored in the postmeta table, where the `post_id` column refers to the attachment row in the posts table.
What's in `postmeta` table
--------------------------
For example, the `"alt"` attribute is stored in a meta field that has the key **`'_wp_attachment_image_alt'`**.
The meta field with key **`'_wp_attached_file'`** contains the relative path (to content folder) of the uploaded file.
That is used to build the attachment URL and path, in functions like [`wp_get_attachment_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_url/), [`wp_get_attachment_image_src()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/), [`get_attached_file()`](https://developer.wordpress.org/reference/functions/get_attached_file/) and so on.
Finally, the field `'_wp_attachment_metadata'` contains different information (in a serialized array in the database):
* The image size (under keys `'width'` and `'height'`)
* Information about **intermediate sizes**
Intermediate sizes
------------------
In fact, every time an image is uploaded, WordPress creates different copies of the image in different sizes.
Please read **[this answer](https://wordpress.stackexchange.com/questions/108572/set-post-thumbnail-size-vs-add-image-size/108583#108583)** for more details.
The key `"sizes"` in the `'_wp_attachment_metadata'` field contain an array with information on all generated images: the file created, the size (width and height) and so on.
Note that the preferred way to get information from `'_wp_attachment_metadata'` is not using the *common* `get_post_meta()` but the specific [`wp_get_attachment_metadata()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/), as it triggers a filter.
If you are interested in the information about a specific generated image, the function [`image_get_intermediate_size()`](https://developer.wordpress.org/reference/functions/image_get_intermediate_size/) will be handy.
Use specific functions
----------------------
Generally speaking, if you need information on an attachment, use the specific functions and avoid pulling data from the database; it is harder and does not triggers hooks, possibly breaking core, theme and plugins compatibility.
There are *a lot* of functions in WordPress to work with attachments, [this](https://developer.wordpress.org/?s=attachment&post_type[]=wp-parser-function) should give you an idea...
However, main functions are all listed in this answer.
|
194,134 |
<p>I don't know when or why but this tags are inserted on my wordpress head automatically and they are adding style that disturb my layout:</p>
<pre><code><meta name="generator" content="WordPress 4.2.2">
<style type="text/css" media="screen">
html { margin-top: 32px !important; }
* html body { margin-top: 32px !important; }
@media screen and ( max-width: 782px ) {
html { margin-top: 46px !important; }
* html body { margin-top: 46px !important; }
}
</style>
</code></pre>
<p>How can I remove it? It is annoying!
Actually the generator is the minor of my problems. Look at all the things that are there:
<img src="https://i.stack.imgur.com/s7JYu.png" alt="enter image description here" /></p>
<p>The reason why I added wp-head on the first place was because I wanted to use a SEO plugin, but this gets inyected even without that plugin enabled.</p>
|
[
{
"answer_id": 194092,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 1,
"selected": false,
"text": "<p>First is showing the attachment file path, second is file attributes size, type, height, width etc.</p>\n\n<p>Thanks</p>\n\n<p>attachment in wp_post shows the attachment basic details title, time, author etc. </p>\n\n<p>wp_postmeta shows attachment all other details for example attachment would be text, pdf, image etc so it having different meta data for different types of posts.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 194119,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": false,
"text": "<h1>An attachment <em>is</em> a Post</h1>\n\n<p>The posts table contains information on the attachment <em>post</em>.</p>\n\n<p>In WordPress every uploaded media has it's own post entry, where <code>post_type</code> is <code>'attachment'</code> and <code>post_status</code> is <code>'inherit'</code>.</p>\n\n<p>In fact, you can get attachment post types using functions used to get other post types, like post, page or any CPT.</p>\n\n<p>That includes <code>WP_Query</code>, <code>get_posts()</code> and <code>get_post()</code>.</p>\n\n<h2>What's in <code>posts</code> table</h2>\n\n<p>For every attachment post</p>\n\n<ul>\n<li><code>post_title</code> column is used for attachment <em>title</em></li>\n<li><code>post_excerpt</code> is used for attachment <em>caption</em></li>\n<li><code>post_content</code> is used for attachment <em>description</em></li>\n</ul>\n\n<p>Note that attachment post type may have a <code>post_parent</code> that points to the ID of the post where the attachment was uploaded from.</p>\n\n<p>For example:</p>\n\n<pre><code>get_posts( 'post_type=attachment&post_parent=10' );\n</code></pre>\n\n<p>Retrieve all the post objects for attachments loaded from the edit page of the post with ID <code>10</code>;</p>\n\n<h1>An attachment is <em>not only</em> a Post</h1>\n\n<p>However, there is information for media (especially images) that simply doesn't fit the posts table.</p>\n\n<p>All this information is stored in the postmeta table, where the <code>post_id</code> column refers to the attachment row in the posts table.</p>\n\n<h2>What's in <code>postmeta</code> table</h2>\n\n<p>For example, the <code>\"alt\"</code> attribute is stored in a meta field that has the key <strong><code>'_wp_attachment_image_alt'</code></strong>.</p>\n\n<p>The meta field with key <strong><code>'_wp_attached_file'</code></strong> contains the relative path (to content folder) of the uploaded file.</p>\n\n<p>That is used to build the attachment URL and path, in functions like <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_url/\" rel=\"noreferrer\"><code>wp_get_attachment_url()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"noreferrer\"><code>wp_get_attachment_image_src()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/get_attached_file/\" rel=\"noreferrer\"><code>get_attached_file()</code></a> and so on.</p>\n\n<p>Finally, the field <code>'_wp_attachment_metadata'</code> contains different information (in a serialized array in the database):</p>\n\n<ul>\n<li>The image size (under keys <code>'width'</code> and <code>'height'</code>)</li>\n<li>Information about <strong>intermediate sizes</strong></li>\n</ul>\n\n<h2>Intermediate sizes</h2>\n\n<p>In fact, every time an image is uploaded, WordPress creates different copies of the image in different sizes.</p>\n\n<p>Please read <strong><a href=\"https://wordpress.stackexchange.com/questions/108572/set-post-thumbnail-size-vs-add-image-size/108583#108583\">this answer</a></strong> for more details.</p>\n\n<p>The key <code>\"sizes\"</code> in the <code>'_wp_attachment_metadata'</code> field contain an array with information on all generated images: the file created, the size (width and height) and so on.</p>\n\n<p>Note that the preferred way to get information from <code>'_wp_attachment_metadata'</code> is not using the <em>common</em> <code>get_post_meta()</code> but the specific <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"noreferrer\"><code>wp_get_attachment_metadata()</code></a>, as it triggers a filter.</p>\n\n<p>If you are interested in the information about a specific generated image, the function <a href=\"https://developer.wordpress.org/reference/functions/image_get_intermediate_size/\" rel=\"noreferrer\"><code>image_get_intermediate_size()</code></a> will be handy.</p>\n\n<h2>Use specific functions</h2>\n\n<p>Generally speaking, if you need information on an attachment, use the specific functions and avoid pulling data from the database; it is harder and does not triggers hooks, possibly breaking core, theme and plugins compatibility.</p>\n\n<p>There are <em>a lot</em> of functions in WordPress to work with attachments, <a href=\"https://developer.wordpress.org/?s=attachment&post_type[]=wp-parser-function\" rel=\"noreferrer\">this</a> should give you an idea...</p>\n\n<p>However, main functions are all listed in this answer.</p>\n"
}
] |
2015/07/10
|
[
"https://wordpress.stackexchange.com/questions/194134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75995/"
] |
I don't know when or why but this tags are inserted on my wordpress head automatically and they are adding style that disturb my layout:
```
<meta name="generator" content="WordPress 4.2.2">
<style type="text/css" media="screen">
html { margin-top: 32px !important; }
* html body { margin-top: 32px !important; }
@media screen and ( max-width: 782px ) {
html { margin-top: 46px !important; }
* html body { margin-top: 46px !important; }
}
</style>
```
How can I remove it? It is annoying!
Actually the generator is the minor of my problems. Look at all the things that are there:

The reason why I added wp-head on the first place was because I wanted to use a SEO plugin, but this gets inyected even without that plugin enabled.
|
An attachment *is* a Post
=========================
The posts table contains information on the attachment *post*.
In WordPress every uploaded media has it's own post entry, where `post_type` is `'attachment'` and `post_status` is `'inherit'`.
In fact, you can get attachment post types using functions used to get other post types, like post, page or any CPT.
That includes `WP_Query`, `get_posts()` and `get_post()`.
What's in `posts` table
-----------------------
For every attachment post
* `post_title` column is used for attachment *title*
* `post_excerpt` is used for attachment *caption*
* `post_content` is used for attachment *description*
Note that attachment post type may have a `post_parent` that points to the ID of the post where the attachment was uploaded from.
For example:
```
get_posts( 'post_type=attachment&post_parent=10' );
```
Retrieve all the post objects for attachments loaded from the edit page of the post with ID `10`;
An attachment is *not only* a Post
==================================
However, there is information for media (especially images) that simply doesn't fit the posts table.
All this information is stored in the postmeta table, where the `post_id` column refers to the attachment row in the posts table.
What's in `postmeta` table
--------------------------
For example, the `"alt"` attribute is stored in a meta field that has the key **`'_wp_attachment_image_alt'`**.
The meta field with key **`'_wp_attached_file'`** contains the relative path (to content folder) of the uploaded file.
That is used to build the attachment URL and path, in functions like [`wp_get_attachment_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_url/), [`wp_get_attachment_image_src()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/), [`get_attached_file()`](https://developer.wordpress.org/reference/functions/get_attached_file/) and so on.
Finally, the field `'_wp_attachment_metadata'` contains different information (in a serialized array in the database):
* The image size (under keys `'width'` and `'height'`)
* Information about **intermediate sizes**
Intermediate sizes
------------------
In fact, every time an image is uploaded, WordPress creates different copies of the image in different sizes.
Please read **[this answer](https://wordpress.stackexchange.com/questions/108572/set-post-thumbnail-size-vs-add-image-size/108583#108583)** for more details.
The key `"sizes"` in the `'_wp_attachment_metadata'` field contain an array with information on all generated images: the file created, the size (width and height) and so on.
Note that the preferred way to get information from `'_wp_attachment_metadata'` is not using the *common* `get_post_meta()` but the specific [`wp_get_attachment_metadata()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/), as it triggers a filter.
If you are interested in the information about a specific generated image, the function [`image_get_intermediate_size()`](https://developer.wordpress.org/reference/functions/image_get_intermediate_size/) will be handy.
Use specific functions
----------------------
Generally speaking, if you need information on an attachment, use the specific functions and avoid pulling data from the database; it is harder and does not triggers hooks, possibly breaking core, theme and plugins compatibility.
There are *a lot* of functions in WordPress to work with attachments, [this](https://developer.wordpress.org/?s=attachment&post_type[]=wp-parser-function) should give you an idea...
However, main functions are all listed in this answer.
|
194,146 |
<p>My WordPress site displays featured images at the top of each post. Here's the PHP code from <code>post.php</code> that generates the featured image.</p>
<pre><code><?php if ( current_theme_supports( 'get-the-image' ) ) get_the_image( array( 'meta_key' => 'Thumbnail', 'size' => 'single-thumbnail', 'link_to_post' => false, 'image_class' => 'featured', 'attachment' => false ) ); ?>
</code></pre>
<p>This code just outputs a standard <code><img></code> tag into the page. For example:</p>
<pre><code><img src="http://www.ericanastas.com/wp-content/uploads/2015/07/2015-04-10_190211-636x460.png" alt="Parkmerced Block 22 Geometry" class="single-thumbnail featured">
</code></pre>
<p>However, other images that I add to the content of a post show as a LightBox when clicked. Here's the HTML for one of these images.</p>
<pre><code><a href="http://www.ericanastas.com/wp-content/uploads/2015/07/2015-04-10_190211.png" rel="lightbox">
<img class="alignnone wp-image-2770 size-single-thumbnail" src="http://www.ericanastas.com/wp-content/uploads/2015/07/2015-04-10_190211-636x460.png" alt="2015-04-10_190211" width="636" height="460" style="opacity: 1;">
</a>
</code></pre>
<p>I would like to add the same LightBox functionality to the featured image at the top of each post. I'm familiar with HTML/CSS/JavaScript but am very new to PHP and WordPress. Can someone help me figure out what code I need to add to get this to work?</p>
|
[
{
"answer_id": 194092,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 1,
"selected": false,
"text": "<p>First is showing the attachment file path, second is file attributes size, type, height, width etc.</p>\n\n<p>Thanks</p>\n\n<p>attachment in wp_post shows the attachment basic details title, time, author etc. </p>\n\n<p>wp_postmeta shows attachment all other details for example attachment would be text, pdf, image etc so it having different meta data for different types of posts.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 194119,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": false,
"text": "<h1>An attachment <em>is</em> a Post</h1>\n\n<p>The posts table contains information on the attachment <em>post</em>.</p>\n\n<p>In WordPress every uploaded media has it's own post entry, where <code>post_type</code> is <code>'attachment'</code> and <code>post_status</code> is <code>'inherit'</code>.</p>\n\n<p>In fact, you can get attachment post types using functions used to get other post types, like post, page or any CPT.</p>\n\n<p>That includes <code>WP_Query</code>, <code>get_posts()</code> and <code>get_post()</code>.</p>\n\n<h2>What's in <code>posts</code> table</h2>\n\n<p>For every attachment post</p>\n\n<ul>\n<li><code>post_title</code> column is used for attachment <em>title</em></li>\n<li><code>post_excerpt</code> is used for attachment <em>caption</em></li>\n<li><code>post_content</code> is used for attachment <em>description</em></li>\n</ul>\n\n<p>Note that attachment post type may have a <code>post_parent</code> that points to the ID of the post where the attachment was uploaded from.</p>\n\n<p>For example:</p>\n\n<pre><code>get_posts( 'post_type=attachment&post_parent=10' );\n</code></pre>\n\n<p>Retrieve all the post objects for attachments loaded from the edit page of the post with ID <code>10</code>;</p>\n\n<h1>An attachment is <em>not only</em> a Post</h1>\n\n<p>However, there is information for media (especially images) that simply doesn't fit the posts table.</p>\n\n<p>All this information is stored in the postmeta table, where the <code>post_id</code> column refers to the attachment row in the posts table.</p>\n\n<h2>What's in <code>postmeta</code> table</h2>\n\n<p>For example, the <code>\"alt\"</code> attribute is stored in a meta field that has the key <strong><code>'_wp_attachment_image_alt'</code></strong>.</p>\n\n<p>The meta field with key <strong><code>'_wp_attached_file'</code></strong> contains the relative path (to content folder) of the uploaded file.</p>\n\n<p>That is used to build the attachment URL and path, in functions like <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_url/\" rel=\"noreferrer\"><code>wp_get_attachment_url()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"noreferrer\"><code>wp_get_attachment_image_src()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/get_attached_file/\" rel=\"noreferrer\"><code>get_attached_file()</code></a> and so on.</p>\n\n<p>Finally, the field <code>'_wp_attachment_metadata'</code> contains different information (in a serialized array in the database):</p>\n\n<ul>\n<li>The image size (under keys <code>'width'</code> and <code>'height'</code>)</li>\n<li>Information about <strong>intermediate sizes</strong></li>\n</ul>\n\n<h2>Intermediate sizes</h2>\n\n<p>In fact, every time an image is uploaded, WordPress creates different copies of the image in different sizes.</p>\n\n<p>Please read <strong><a href=\"https://wordpress.stackexchange.com/questions/108572/set-post-thumbnail-size-vs-add-image-size/108583#108583\">this answer</a></strong> for more details.</p>\n\n<p>The key <code>\"sizes\"</code> in the <code>'_wp_attachment_metadata'</code> field contain an array with information on all generated images: the file created, the size (width and height) and so on.</p>\n\n<p>Note that the preferred way to get information from <code>'_wp_attachment_metadata'</code> is not using the <em>common</em> <code>get_post_meta()</code> but the specific <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"noreferrer\"><code>wp_get_attachment_metadata()</code></a>, as it triggers a filter.</p>\n\n<p>If you are interested in the information about a specific generated image, the function <a href=\"https://developer.wordpress.org/reference/functions/image_get_intermediate_size/\" rel=\"noreferrer\"><code>image_get_intermediate_size()</code></a> will be handy.</p>\n\n<h2>Use specific functions</h2>\n\n<p>Generally speaking, if you need information on an attachment, use the specific functions and avoid pulling data from the database; it is harder and does not triggers hooks, possibly breaking core, theme and plugins compatibility.</p>\n\n<p>There are <em>a lot</em> of functions in WordPress to work with attachments, <a href=\"https://developer.wordpress.org/?s=attachment&post_type[]=wp-parser-function\" rel=\"noreferrer\">this</a> should give you an idea...</p>\n\n<p>However, main functions are all listed in this answer.</p>\n"
}
] |
2015/07/10
|
[
"https://wordpress.stackexchange.com/questions/194146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76000/"
] |
My WordPress site displays featured images at the top of each post. Here's the PHP code from `post.php` that generates the featured image.
```
<?php if ( current_theme_supports( 'get-the-image' ) ) get_the_image( array( 'meta_key' => 'Thumbnail', 'size' => 'single-thumbnail', 'link_to_post' => false, 'image_class' => 'featured', 'attachment' => false ) ); ?>
```
This code just outputs a standard `<img>` tag into the page. For example:
```
<img src="http://www.ericanastas.com/wp-content/uploads/2015/07/2015-04-10_190211-636x460.png" alt="Parkmerced Block 22 Geometry" class="single-thumbnail featured">
```
However, other images that I add to the content of a post show as a LightBox when clicked. Here's the HTML for one of these images.
```
<a href="http://www.ericanastas.com/wp-content/uploads/2015/07/2015-04-10_190211.png" rel="lightbox">
<img class="alignnone wp-image-2770 size-single-thumbnail" src="http://www.ericanastas.com/wp-content/uploads/2015/07/2015-04-10_190211-636x460.png" alt="2015-04-10_190211" width="636" height="460" style="opacity: 1;">
</a>
```
I would like to add the same LightBox functionality to the featured image at the top of each post. I'm familiar with HTML/CSS/JavaScript but am very new to PHP and WordPress. Can someone help me figure out what code I need to add to get this to work?
|
An attachment *is* a Post
=========================
The posts table contains information on the attachment *post*.
In WordPress every uploaded media has it's own post entry, where `post_type` is `'attachment'` and `post_status` is `'inherit'`.
In fact, you can get attachment post types using functions used to get other post types, like post, page or any CPT.
That includes `WP_Query`, `get_posts()` and `get_post()`.
What's in `posts` table
-----------------------
For every attachment post
* `post_title` column is used for attachment *title*
* `post_excerpt` is used for attachment *caption*
* `post_content` is used for attachment *description*
Note that attachment post type may have a `post_parent` that points to the ID of the post where the attachment was uploaded from.
For example:
```
get_posts( 'post_type=attachment&post_parent=10' );
```
Retrieve all the post objects for attachments loaded from the edit page of the post with ID `10`;
An attachment is *not only* a Post
==================================
However, there is information for media (especially images) that simply doesn't fit the posts table.
All this information is stored in the postmeta table, where the `post_id` column refers to the attachment row in the posts table.
What's in `postmeta` table
--------------------------
For example, the `"alt"` attribute is stored in a meta field that has the key **`'_wp_attachment_image_alt'`**.
The meta field with key **`'_wp_attached_file'`** contains the relative path (to content folder) of the uploaded file.
That is used to build the attachment URL and path, in functions like [`wp_get_attachment_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_url/), [`wp_get_attachment_image_src()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/), [`get_attached_file()`](https://developer.wordpress.org/reference/functions/get_attached_file/) and so on.
Finally, the field `'_wp_attachment_metadata'` contains different information (in a serialized array in the database):
* The image size (under keys `'width'` and `'height'`)
* Information about **intermediate sizes**
Intermediate sizes
------------------
In fact, every time an image is uploaded, WordPress creates different copies of the image in different sizes.
Please read **[this answer](https://wordpress.stackexchange.com/questions/108572/set-post-thumbnail-size-vs-add-image-size/108583#108583)** for more details.
The key `"sizes"` in the `'_wp_attachment_metadata'` field contain an array with information on all generated images: the file created, the size (width and height) and so on.
Note that the preferred way to get information from `'_wp_attachment_metadata'` is not using the *common* `get_post_meta()` but the specific [`wp_get_attachment_metadata()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/), as it triggers a filter.
If you are interested in the information about a specific generated image, the function [`image_get_intermediate_size()`](https://developer.wordpress.org/reference/functions/image_get_intermediate_size/) will be handy.
Use specific functions
----------------------
Generally speaking, if you need information on an attachment, use the specific functions and avoid pulling data from the database; it is harder and does not triggers hooks, possibly breaking core, theme and plugins compatibility.
There are *a lot* of functions in WordPress to work with attachments, [this](https://developer.wordpress.org/?s=attachment&post_type[]=wp-parser-function) should give you an idea...
However, main functions are all listed in this answer.
|
194,156 |
<p>I have script to show list tags from category and works very well. </p>
<pre><code><ul class="inline-list">
<?php
query_posts('category_name=lain-lain');
if (have_posts()) : while (have_posts()) : the_post();
if( get_the_tag_list() ){
echo $posttags = get_the_tag_list('<li>','</li><li>','</li>');
}
endwhile; endif;
wp_reset_query();
?>
</ul>
</code></pre>
<p>It's possible to make no duplicate of tags and limit only 10 tags?</p>
<p>Please help </p>
<p>Thank you</p>
|
[
{
"answer_id": 194092,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 1,
"selected": false,
"text": "<p>First is showing the attachment file path, second is file attributes size, type, height, width etc.</p>\n\n<p>Thanks</p>\n\n<p>attachment in wp_post shows the attachment basic details title, time, author etc. </p>\n\n<p>wp_postmeta shows attachment all other details for example attachment would be text, pdf, image etc so it having different meta data for different types of posts.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 194119,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": false,
"text": "<h1>An attachment <em>is</em> a Post</h1>\n\n<p>The posts table contains information on the attachment <em>post</em>.</p>\n\n<p>In WordPress every uploaded media has it's own post entry, where <code>post_type</code> is <code>'attachment'</code> and <code>post_status</code> is <code>'inherit'</code>.</p>\n\n<p>In fact, you can get attachment post types using functions used to get other post types, like post, page or any CPT.</p>\n\n<p>That includes <code>WP_Query</code>, <code>get_posts()</code> and <code>get_post()</code>.</p>\n\n<h2>What's in <code>posts</code> table</h2>\n\n<p>For every attachment post</p>\n\n<ul>\n<li><code>post_title</code> column is used for attachment <em>title</em></li>\n<li><code>post_excerpt</code> is used for attachment <em>caption</em></li>\n<li><code>post_content</code> is used for attachment <em>description</em></li>\n</ul>\n\n<p>Note that attachment post type may have a <code>post_parent</code> that points to the ID of the post where the attachment was uploaded from.</p>\n\n<p>For example:</p>\n\n<pre><code>get_posts( 'post_type=attachment&post_parent=10' );\n</code></pre>\n\n<p>Retrieve all the post objects for attachments loaded from the edit page of the post with ID <code>10</code>;</p>\n\n<h1>An attachment is <em>not only</em> a Post</h1>\n\n<p>However, there is information for media (especially images) that simply doesn't fit the posts table.</p>\n\n<p>All this information is stored in the postmeta table, where the <code>post_id</code> column refers to the attachment row in the posts table.</p>\n\n<h2>What's in <code>postmeta</code> table</h2>\n\n<p>For example, the <code>\"alt\"</code> attribute is stored in a meta field that has the key <strong><code>'_wp_attachment_image_alt'</code></strong>.</p>\n\n<p>The meta field with key <strong><code>'_wp_attached_file'</code></strong> contains the relative path (to content folder) of the uploaded file.</p>\n\n<p>That is used to build the attachment URL and path, in functions like <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_url/\" rel=\"noreferrer\"><code>wp_get_attachment_url()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"noreferrer\"><code>wp_get_attachment_image_src()</code></a>, <a href=\"https://developer.wordpress.org/reference/functions/get_attached_file/\" rel=\"noreferrer\"><code>get_attached_file()</code></a> and so on.</p>\n\n<p>Finally, the field <code>'_wp_attachment_metadata'</code> contains different information (in a serialized array in the database):</p>\n\n<ul>\n<li>The image size (under keys <code>'width'</code> and <code>'height'</code>)</li>\n<li>Information about <strong>intermediate sizes</strong></li>\n</ul>\n\n<h2>Intermediate sizes</h2>\n\n<p>In fact, every time an image is uploaded, WordPress creates different copies of the image in different sizes.</p>\n\n<p>Please read <strong><a href=\"https://wordpress.stackexchange.com/questions/108572/set-post-thumbnail-size-vs-add-image-size/108583#108583\">this answer</a></strong> for more details.</p>\n\n<p>The key <code>\"sizes\"</code> in the <code>'_wp_attachment_metadata'</code> field contain an array with information on all generated images: the file created, the size (width and height) and so on.</p>\n\n<p>Note that the preferred way to get information from <code>'_wp_attachment_metadata'</code> is not using the <em>common</em> <code>get_post_meta()</code> but the specific <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"noreferrer\"><code>wp_get_attachment_metadata()</code></a>, as it triggers a filter.</p>\n\n<p>If you are interested in the information about a specific generated image, the function <a href=\"https://developer.wordpress.org/reference/functions/image_get_intermediate_size/\" rel=\"noreferrer\"><code>image_get_intermediate_size()</code></a> will be handy.</p>\n\n<h2>Use specific functions</h2>\n\n<p>Generally speaking, if you need information on an attachment, use the specific functions and avoid pulling data from the database; it is harder and does not triggers hooks, possibly breaking core, theme and plugins compatibility.</p>\n\n<p>There are <em>a lot</em> of functions in WordPress to work with attachments, <a href=\"https://developer.wordpress.org/?s=attachment&post_type[]=wp-parser-function\" rel=\"noreferrer\">this</a> should give you an idea...</p>\n\n<p>However, main functions are all listed in this answer.</p>\n"
}
] |
2015/07/11
|
[
"https://wordpress.stackexchange.com/questions/194156",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45645/"
] |
I have script to show list tags from category and works very well.
```
<ul class="inline-list">
<?php
query_posts('category_name=lain-lain');
if (have_posts()) : while (have_posts()) : the_post();
if( get_the_tag_list() ){
echo $posttags = get_the_tag_list('<li>','</li><li>','</li>');
}
endwhile; endif;
wp_reset_query();
?>
</ul>
```
It's possible to make no duplicate of tags and limit only 10 tags?
Please help
Thank you
|
An attachment *is* a Post
=========================
The posts table contains information on the attachment *post*.
In WordPress every uploaded media has it's own post entry, where `post_type` is `'attachment'` and `post_status` is `'inherit'`.
In fact, you can get attachment post types using functions used to get other post types, like post, page or any CPT.
That includes `WP_Query`, `get_posts()` and `get_post()`.
What's in `posts` table
-----------------------
For every attachment post
* `post_title` column is used for attachment *title*
* `post_excerpt` is used for attachment *caption*
* `post_content` is used for attachment *description*
Note that attachment post type may have a `post_parent` that points to the ID of the post where the attachment was uploaded from.
For example:
```
get_posts( 'post_type=attachment&post_parent=10' );
```
Retrieve all the post objects for attachments loaded from the edit page of the post with ID `10`;
An attachment is *not only* a Post
==================================
However, there is information for media (especially images) that simply doesn't fit the posts table.
All this information is stored in the postmeta table, where the `post_id` column refers to the attachment row in the posts table.
What's in `postmeta` table
--------------------------
For example, the `"alt"` attribute is stored in a meta field that has the key **`'_wp_attachment_image_alt'`**.
The meta field with key **`'_wp_attached_file'`** contains the relative path (to content folder) of the uploaded file.
That is used to build the attachment URL and path, in functions like [`wp_get_attachment_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_url/), [`wp_get_attachment_image_src()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/), [`get_attached_file()`](https://developer.wordpress.org/reference/functions/get_attached_file/) and so on.
Finally, the field `'_wp_attachment_metadata'` contains different information (in a serialized array in the database):
* The image size (under keys `'width'` and `'height'`)
* Information about **intermediate sizes**
Intermediate sizes
------------------
In fact, every time an image is uploaded, WordPress creates different copies of the image in different sizes.
Please read **[this answer](https://wordpress.stackexchange.com/questions/108572/set-post-thumbnail-size-vs-add-image-size/108583#108583)** for more details.
The key `"sizes"` in the `'_wp_attachment_metadata'` field contain an array with information on all generated images: the file created, the size (width and height) and so on.
Note that the preferred way to get information from `'_wp_attachment_metadata'` is not using the *common* `get_post_meta()` but the specific [`wp_get_attachment_metadata()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/), as it triggers a filter.
If you are interested in the information about a specific generated image, the function [`image_get_intermediate_size()`](https://developer.wordpress.org/reference/functions/image_get_intermediate_size/) will be handy.
Use specific functions
----------------------
Generally speaking, if you need information on an attachment, use the specific functions and avoid pulling data from the database; it is harder and does not triggers hooks, possibly breaking core, theme and plugins compatibility.
There are *a lot* of functions in WordPress to work with attachments, [this](https://developer.wordpress.org/?s=attachment&post_type[]=wp-parser-function) should give you an idea...
However, main functions are all listed in this answer.
|
194,171 |
<p>I'm creating one wordpress template. Required information added in wordpress header.php, footer.php and everything was fine. Then i added one page. But while viewing the page there was a small problem just above the footer. After checking i found following code creating all the problems</p>
<pre><code><br class="clear">
</code></pre>
<p>But i didn't added that in page content. Somebody please tell me from where this thing came, and how to remove this?</p>
|
[
{
"answer_id": 194197,
"author": "emilushi",
"author_id": 63983,
"author_profile": "https://wordpress.stackexchange.com/users/63983",
"pm_score": -1,
"selected": false,
"text": "<p>at your theme functions add this line: <code>remove_filter('the_content', 'wpautop');</code></p>\n"
},
{
"answer_id": 194220,
"author": "Zak",
"author_id": 59760,
"author_profile": "https://wordpress.stackexchange.com/users/59760",
"pm_score": 0,
"selected": false,
"text": "<p>I afraid that added by some custom function or JavaScript because WordPress never add that tag by default. So use CSS to hide that element if you don't find that script</p>\n"
}
] |
2015/07/11
|
[
"https://wordpress.stackexchange.com/questions/194171",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75994/"
] |
I'm creating one wordpress template. Required information added in wordpress header.php, footer.php and everything was fine. Then i added one page. But while viewing the page there was a small problem just above the footer. After checking i found following code creating all the problems
```
<br class="clear">
```
But i didn't added that in page content. Somebody please tell me from where this thing came, and how to remove this?
|
I afraid that added by some custom function or JavaScript because WordPress never add that tag by default. So use CSS to hide that element if you don't find that script
|
194,203 |
<p>I am using the following code in functions.php of the child theme to include a file</p>
<pre><code>require_once(get_stylesheet_directory_uri().'/functions/taxonomy-images.php');
</code></pre>
<p>But i get these warnings and fatal error</p>
<pre><code>Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\xampp\htdocs\yakoo\wp-content\themes\listify-child\functions.php on line 68
Warning: require_once(http://localhost/yakoo/wp-content/themes/listify-child/functions/taxonomy-images.php): failed to open stream: no suitable wrapper could be found in C:\xampp\htdocs\yakoo\wp-content\themes\listify-child\functions.php on line 68
Fatal error: require_once(): Failed opening required 'http://localhost/yakoo/wp-content/themes/listify-child/functions/taxonomy-images.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\yakoo\wp-content\themes\listify-child\functions.php on line 68
</code></pre>
<p>No idea what s going wrong.</p>
<p>Please help</p>
|
[
{
"answer_id": 194206,
"author": "kanenas",
"author_id": 45047,
"author_profile": "https://wordpress.stackexchange.com/users/45047",
"pm_score": 2,
"selected": false,
"text": "<pre><code>get_stylesheet_directory_uri()\n</code></pre>\n\n<p>Note that this returns a properly-formed URI; in other words, it will be a web-address (starting with http:// or https:// for SSL). As such, it is most appropriately used for links, referencing additional stylesheets, or probably most commonly, images.</p>\n\n<pre><code>get_stylesheet_directory()\n</code></pre>\n\n<p>Retrieve stylesheet directory Path for the current theme/child theme.<br>\n<strong>Note</strong>: Does not contain a trailing slash.\nReturns an absolute server path (eg: /home/user/public_html/wp-content/themes/my_theme), not a URI.</p>\n\n<p>So I guess this</p>\n\n<pre><code>require_once( get_stylesheet_directory() . '/functions/taxonomy-images.php' );\n</code></pre>\n\n<p>should be fine.</p>\n"
},
{
"answer_id": 194225,
"author": "Rituparna sonowal",
"author_id": 71232,
"author_profile": "https://wordpress.stackexchange.com/users/71232",
"pm_score": 0,
"selected": false,
"text": "<p>Try this way, It works:</p>\n\n<pre><code> require_once dirname(__FILE__) . '/functions/taxonomy-images.php';\n</code></pre>\n"
}
] |
2015/07/11
|
[
"https://wordpress.stackexchange.com/questions/194203",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55034/"
] |
I am using the following code in functions.php of the child theme to include a file
```
require_once(get_stylesheet_directory_uri().'/functions/taxonomy-images.php');
```
But i get these warnings and fatal error
```
Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\xampp\htdocs\yakoo\wp-content\themes\listify-child\functions.php on line 68
Warning: require_once(http://localhost/yakoo/wp-content/themes/listify-child/functions/taxonomy-images.php): failed to open stream: no suitable wrapper could be found in C:\xampp\htdocs\yakoo\wp-content\themes\listify-child\functions.php on line 68
Fatal error: require_once(): Failed opening required 'http://localhost/yakoo/wp-content/themes/listify-child/functions/taxonomy-images.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\yakoo\wp-content\themes\listify-child\functions.php on line 68
```
No idea what s going wrong.
Please help
|
```
get_stylesheet_directory_uri()
```
Note that this returns a properly-formed URI; in other words, it will be a web-address (starting with http:// or https:// for SSL). As such, it is most appropriately used for links, referencing additional stylesheets, or probably most commonly, images.
```
get_stylesheet_directory()
```
Retrieve stylesheet directory Path for the current theme/child theme.
**Note**: Does not contain a trailing slash.
Returns an absolute server path (eg: /home/user/public\_html/wp-content/themes/my\_theme), not a URI.
So I guess this
```
require_once( get_stylesheet_directory() . '/functions/taxonomy-images.php' );
```
should be fine.
|
194,204 |
<p>I have a news system with a thumbnail and a box on it that show the category related to the news, using <code><?php the_category(', '); ?></code>
This worked fine using only one category for each news, but since I downloaded SEO by Yoast, I added a breadcrumb at the top of my page.php and single.php and did a hierarchy for my news.</p>
<p>So now, since I have a hierarchy type like this "Home > News > Sub-category > Sub-sub category".</p>
<p>What should I add instead of the_category to only show the "sub-sub-category" in the news box ? Is this possible ?</p>
<p><strong>EDIT :</strong></p>
<p><strong>Example 1</strong> (before) calling the category with the post set under only 1 category : </p>
<p>html</p>
<pre><code><div class="news-box">
<div class="category-box">
<h2><ul class="post-categories">
<li><a href="http://#.fr/category/News/" rel="tag">News</a></li></ul></h2>
<!--Called using <?php the_category(', '); ?> when only one category is set-->
</div>
</div>
</code></pre>
<p>css</p>
<pre><code>.news-box {
background-color:#777;
height:200px;
position:relative;
}
.category-box {
background-color:#FFFFFF;
position:absolute;
bottom:10px;
left:10px;
text-transform:uppercase;
}
</code></pre>
<p><a href="https://jsfiddle.net/rpoyxvp9/" rel="nofollow">https://jsfiddle.net/rpoyxvp9/</a></p>
<p>Which worked fine so far</p>
<p><strong>Example 2</strong> (now) calling the category with the post set under multiple sub-categories :</p>
<p>html</p>
<pre><code><div class="news-box">
<div class="category-box">
<h2><ul class="post-categories">
<li><a href="http://#.fr/category/news/anime/" rel="tag">Anime</a></li>
<li><a href="http://#.fr/category/news/" rel="tag">News</a></li></ul></h2>
<!--Called using <?php the_category(', '); ?> when multiple categories are set-->
</div>
</div>
</code></pre>
<p>css</p>
<pre><code>.news-box {
background-color:#777;
height:200px;
position:relative;
}
.category-box {
background-color:#FFFFFF;
position:absolute;
bottom:10px;
left:10px;
text-transform:uppercase;
}
</code></pre>
<p><a href="https://jsfiddle.net/gthsa5mx/" rel="nofollow">https://jsfiddle.net/gthsa5mx/</a></p>
<p>Which doesn't work the way I want, as you can see when multiple categories are set under sub-categories, it shows all the path. But in my example 2, I would like only the sub-category "Anime" to appear on the category-box.</p>
<p>Also, I want it to be called without the <code><li></code>, so you're going to tell me to remove the <code><ul> and <li></code> but I can't since it is automatically called when using <code>the_category(', ');</code>.</p>
|
[
{
"answer_id": 194206,
"author": "kanenas",
"author_id": 45047,
"author_profile": "https://wordpress.stackexchange.com/users/45047",
"pm_score": 2,
"selected": false,
"text": "<pre><code>get_stylesheet_directory_uri()\n</code></pre>\n\n<p>Note that this returns a properly-formed URI; in other words, it will be a web-address (starting with http:// or https:// for SSL). As such, it is most appropriately used for links, referencing additional stylesheets, or probably most commonly, images.</p>\n\n<pre><code>get_stylesheet_directory()\n</code></pre>\n\n<p>Retrieve stylesheet directory Path for the current theme/child theme.<br>\n<strong>Note</strong>: Does not contain a trailing slash.\nReturns an absolute server path (eg: /home/user/public_html/wp-content/themes/my_theme), not a URI.</p>\n\n<p>So I guess this</p>\n\n<pre><code>require_once( get_stylesheet_directory() . '/functions/taxonomy-images.php' );\n</code></pre>\n\n<p>should be fine.</p>\n"
},
{
"answer_id": 194225,
"author": "Rituparna sonowal",
"author_id": 71232,
"author_profile": "https://wordpress.stackexchange.com/users/71232",
"pm_score": 0,
"selected": false,
"text": "<p>Try this way, It works:</p>\n\n<pre><code> require_once dirname(__FILE__) . '/functions/taxonomy-images.php';\n</code></pre>\n"
}
] |
2015/07/11
|
[
"https://wordpress.stackexchange.com/questions/194204",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76033/"
] |
I have a news system with a thumbnail and a box on it that show the category related to the news, using `<?php the_category(', '); ?>`
This worked fine using only one category for each news, but since I downloaded SEO by Yoast, I added a breadcrumb at the top of my page.php and single.php and did a hierarchy for my news.
So now, since I have a hierarchy type like this "Home > News > Sub-category > Sub-sub category".
What should I add instead of the\_category to only show the "sub-sub-category" in the news box ? Is this possible ?
**EDIT :**
**Example 1** (before) calling the category with the post set under only 1 category :
html
```
<div class="news-box">
<div class="category-box">
<h2><ul class="post-categories">
<li><a href="http://#.fr/category/News/" rel="tag">News</a></li></ul></h2>
<!--Called using <?php the_category(', '); ?> when only one category is set-->
</div>
</div>
```
css
```
.news-box {
background-color:#777;
height:200px;
position:relative;
}
.category-box {
background-color:#FFFFFF;
position:absolute;
bottom:10px;
left:10px;
text-transform:uppercase;
}
```
<https://jsfiddle.net/rpoyxvp9/>
Which worked fine so far
**Example 2** (now) calling the category with the post set under multiple sub-categories :
html
```
<div class="news-box">
<div class="category-box">
<h2><ul class="post-categories">
<li><a href="http://#.fr/category/news/anime/" rel="tag">Anime</a></li>
<li><a href="http://#.fr/category/news/" rel="tag">News</a></li></ul></h2>
<!--Called using <?php the_category(', '); ?> when multiple categories are set-->
</div>
</div>
```
css
```
.news-box {
background-color:#777;
height:200px;
position:relative;
}
.category-box {
background-color:#FFFFFF;
position:absolute;
bottom:10px;
left:10px;
text-transform:uppercase;
}
```
<https://jsfiddle.net/gthsa5mx/>
Which doesn't work the way I want, as you can see when multiple categories are set under sub-categories, it shows all the path. But in my example 2, I would like only the sub-category "Anime" to appear on the category-box.
Also, I want it to be called without the `<li>`, so you're going to tell me to remove the `<ul> and <li>` but I can't since it is automatically called when using `the_category(', ');`.
|
```
get_stylesheet_directory_uri()
```
Note that this returns a properly-formed URI; in other words, it will be a web-address (starting with http:// or https:// for SSL). As such, it is most appropriately used for links, referencing additional stylesheets, or probably most commonly, images.
```
get_stylesheet_directory()
```
Retrieve stylesheet directory Path for the current theme/child theme.
**Note**: Does not contain a trailing slash.
Returns an absolute server path (eg: /home/user/public\_html/wp-content/themes/my\_theme), not a URI.
So I guess this
```
require_once( get_stylesheet_directory() . '/functions/taxonomy-images.php' );
```
should be fine.
|
194,267 |
<p>I am making by wonderful page and I want to query a given custom post type called accommodations and display the number of posts in that given location and this what I have e.g (1,110) Accommodation in Newyork</p>
<pre><code><?php
$args = array(
'post_type' => 'accommodations',
'taxonomy' => 'location',
'field' => 'NewYork'
);
$the_query = new WP_Query( $args );
echo $the_query->found_posts;
?>
</code></pre>
<p>but it gives me everything in that custom post type instead</p>
|
[
{
"answer_id": 194269,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>Your query is completely wrong. You should use a proper <code>tax_query</code>. Also note, your query is quite expensive to run to just count posts. Set the <code>fields</code> paremeter to only return post ID's. This saves up to 99.9% on resources.</p>\n\n<p>Just a note, the field parameter inside a <code>tax_query</code> is important. The valid values are <code>slug</code>, <code>term_id</code> and <code>name</code>. This value must correspond with the value passed to the <code>terms</code> parameter. So, if fields are set to <code>slug</code>, you must pass the term slug to <code>terms</code>. Do not use the <code>name</code> parameter, there is a bug in the <code>WP_Tax_Query</code> class where the query fails if a term's name consists of more than one word.</p>\n\n<p>You can try the following</p>\n\n<pre><code> $args = array(\n 'post_type' => 'accommodations',\n 'no_paging' => true, // Gets all posts\n 'fields' => 'ids', // Gets only the post ID's, saves on resources\n 'tax_query' => array(\n array(\n 'taxonomy' => 'location', // Taxonomy name\n 'field' => 'slug', // Field to check, valid values are term_id, slug and name\n 'terms' => 'new-york' // This value must correspond to field value. If slug, use term slug\n )\n ),\n);\n$the_query = new WP_Query( $args );\necho $the_query->found_posts;\n</code></pre>\n"
},
{
"answer_id": 194270,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 0,
"selected": false,
"text": "<p>Based on your question </p>\n\n<blockquote>\n <p>display the number of posts</p>\n</blockquote>\n\n<pre><code>$published_posts = wp_count_posts('accommodations')->publish;\n</code></pre>\n\n<p>This will give you the number of posts published for the accommodations post type.</p>\n"
}
] |
2015/07/12
|
[
"https://wordpress.stackexchange.com/questions/194267",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76073/"
] |
I am making by wonderful page and I want to query a given custom post type called accommodations and display the number of posts in that given location and this what I have e.g (1,110) Accommodation in Newyork
```
<?php
$args = array(
'post_type' => 'accommodations',
'taxonomy' => 'location',
'field' => 'NewYork'
);
$the_query = new WP_Query( $args );
echo $the_query->found_posts;
?>
```
but it gives me everything in that custom post type instead
|
Your query is completely wrong. You should use a proper `tax_query`. Also note, your query is quite expensive to run to just count posts. Set the `fields` paremeter to only return post ID's. This saves up to 99.9% on resources.
Just a note, the field parameter inside a `tax_query` is important. The valid values are `slug`, `term_id` and `name`. This value must correspond with the value passed to the `terms` parameter. So, if fields are set to `slug`, you must pass the term slug to `terms`. Do not use the `name` parameter, there is a bug in the `WP_Tax_Query` class where the query fails if a term's name consists of more than one word.
You can try the following
```
$args = array(
'post_type' => 'accommodations',
'no_paging' => true, // Gets all posts
'fields' => 'ids', // Gets only the post ID's, saves on resources
'tax_query' => array(
array(
'taxonomy' => 'location', // Taxonomy name
'field' => 'slug', // Field to check, valid values are term_id, slug and name
'terms' => 'new-york' // This value must correspond to field value. If slug, use term slug
)
),
);
$the_query = new WP_Query( $args );
echo $the_query->found_posts;
```
|
194,273 |
<p>I have created a WP plugin which uses the query string to pull in page data based on what the visitor has selected. Obviously this 'simulates' additional pages but the page title does not change from the title set in WP Admin.</p>
<p>I have been trying to hook into <code>wp_title</code> to change the title tag on fly but can't get this one working.</p>
<p>The following function works:</p>
<pre><code>public function custom_title($title) {
return 'new title';
}
add_filter( 'wp_title', array($this, 'custom_title'), 20 );
// changes <title> to 'new title'
</code></pre>
<p>As soon as I try to pass a variable to it, it fails.</p>
<pre><code>public function custom_title($title, $new_title) {
return $new_title;
}
</code></pre>
<p>WordPress complains it's missing the 2nd argument, I guess this makes sense since the function is being called at page load... I was hoping I could do something like <code>$this->custom_title($title, 'new title);</code> within my plugin but it doesn't look like that is going to be possible?</p>
<p>I have posted this here because I think it's a general PHP class issue.</p>
<p>Can I globalise a returned variable, e.g. I want to return the 'title' column from a query in another function such as <code>$query->title</code></p>
<p>When the function runs it returns data from the database</p>
<pre><code>public function view_content()
{
$query = $this->db->get_row('SELECT title FROM ...');
$query->title;
}
</code></pre>
<p>I now need $query->title to be set as the page title.</p>
<pre><code>public function custom_title()
{
if($query->title)
{
$new_title = $query->title;
}
}
</code></pre>
<p>A stripped down version of my class:</p>
<pre><code>class FB_Events {
private static $_instance = null;
private $wpdb;
public $_token;
public $file;
public $dir;
public $assets_dir;
public $assets_url;
private $message;
public function __construct($file = '', $version = '1.0.0')
{
global $wpdb;
$this->db = $wpdb;
$this->fb_events_table = $this->db->prefix . 'fb_events';
$this->_version = $version;
$this->_token = 'fb_events';
$this->_db_version = '1.0.0';
$this->file = $file;
$this->dir = dirname($this->file);
$this->assets_dir = trailingslashit($this->dir) . 'assets';
$this->assets_url = esc_url(trailingslashit(plugins_url('/assets/', $this->file)));
register_activation_hook($this->file, array($this, 'install'));
add_action('admin_menu', array($this, 'admin_menu'));
add_action('init', array($this, 'rewrite_rules'), 10, 0);
add_filter('query_vars', array($this, 'event_query_var'), 0, 1);
// Add shortcodes for html output
add_shortcode('fb_events_form', array($this, 'add_event_public'));
add_shortcode('fb_events_display', array($this, 'view_events'));
add_shortcode('fb_events_featured', array($this, 'featured_events'));
}
/**
* Register rewrite rules
* @access public
* @since 1.0.0
* @return void
*/
public function rewrite_rules()
{
add_rewrite_rule('^events/add/?', 'index.php?pagename=events/add', 'top');
add_rewrite_rule('^events/([^/]*)/?','index.php?pagename=events&event=$matches[1]', 'top');
}
/**
* Register event query string
* @access public
* @since 1.0.0
* @return void
*/
public function event_query_var($vars)
{
$vars[] = 'event';
return $vars;
}
/**
* View events from public website
* @access public
* @since 1.0.0
* @return void
*/
public function view_events()
{
$event = get_query_var('event');
if(isset($event) && $event != '')
{
if($event != 'add')
{
$event = $this->db->get_row(
$this->db->prepare("
SELECT e.*, u.display_name AS username
FROM {$this->fb_events_table} AS e
LEFT JOIN {$this->db->prefix}users AS u
ON e.user_id = u.id
WHERE e.slug = %s
", $event)
);
if($event > 0)
{
/**
* *********************************
* NEED TO SET <title> to $event->name
* *********************************
*/
ob_start();
if(isset($event->active) && $event->active == 0)
{
//error
}
else
{
//show the event
}
}
else
{
// event does not exist error
}
}
}
}
/**
* Main FB_Events Instance
* @since 1.0.0
* @static
* @return Main FB_Events instance
*/
public static function instance($file = '', $version = '1.0.0') {
if(is_null(self::$_instance))
{
self::$_instance = new self($file, $version);
}
return self::$_instance;
}
}
</code></pre>
|
[
{
"answer_id": 194284,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you can alter that with a filter on <code>wp_title</code> but you don't provide enough detail about your project to really get a good answer.</p>\n\n<p>There is sample code in the Codex: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title</a></p>\n"
},
{
"answer_id": 244082,
"author": "Will",
"author_id": 38355,
"author_profile": "https://wordpress.stackexchange.com/users/38355",
"pm_score": 3,
"selected": false,
"text": "<p>As of WP 4.4, wp_title is deprecated. If you simply need to override your title tag, pre_get_document_title is the filter you want to use.</p>\n\n<pre><code>add_filter( 'pre_get_document_title', 'generate_custom_title', 10 );\n</code></pre>\n\n<p>and the function would look something like this</p>\n\n<pre><code>function generate_custom_title($title) {\n/* your code to generate the new title and assign the $title var to it... */\nreturn $title; \n}\n</code></pre>\n\n<p>If you're a stickler you'll know that pre_get_document_title doesn't normally take any args; but if you use the Yoast SEO plugin, you'll find out that this function doesn't do anything! So I <em>also</em> hook the 'wpseo_title' filter onto this same function.</p>\n\n<pre><code>add_filter( 'wpseo_title', 'generate_custom_title'), 15 );\n</code></pre>\n\n<p>just in case Yoast is turned on. Code reuse.</p>\n"
},
{
"answer_id": 286749,
"author": "Sandro",
"author_id": 131984,
"author_profile": "https://wordpress.stackexchange.com/users/131984",
"pm_score": 2,
"selected": false,
"text": "<p>I think your original problem was the variable scope. If you want a variable to be \"seen\" inside a php function, you must declare it \"global\" inside that function.\nThis is working for me:</p>\n\n<pre><code>$new_title = 'this is my title';\n\nfunction generate_custom_title($title) {\n global $new_title;\n $title = $new_title;\n return $title; \n }\n\nadd_filter( 'pre_get_document_title', 'generate_custom_title', 10 );\nadd_filter( 'wpseo_title', 'generate_custom_title', 15 );\n\nget_header();\n</code></pre>\n"
}
] |
2015/07/12
|
[
"https://wordpress.stackexchange.com/questions/194273",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74399/"
] |
I have created a WP plugin which uses the query string to pull in page data based on what the visitor has selected. Obviously this 'simulates' additional pages but the page title does not change from the title set in WP Admin.
I have been trying to hook into `wp_title` to change the title tag on fly but can't get this one working.
The following function works:
```
public function custom_title($title) {
return 'new title';
}
add_filter( 'wp_title', array($this, 'custom_title'), 20 );
// changes <title> to 'new title'
```
As soon as I try to pass a variable to it, it fails.
```
public function custom_title($title, $new_title) {
return $new_title;
}
```
WordPress complains it's missing the 2nd argument, I guess this makes sense since the function is being called at page load... I was hoping I could do something like `$this->custom_title($title, 'new title);` within my plugin but it doesn't look like that is going to be possible?
I have posted this here because I think it's a general PHP class issue.
Can I globalise a returned variable, e.g. I want to return the 'title' column from a query in another function such as `$query->title`
When the function runs it returns data from the database
```
public function view_content()
{
$query = $this->db->get_row('SELECT title FROM ...');
$query->title;
}
```
I now need $query->title to be set as the page title.
```
public function custom_title()
{
if($query->title)
{
$new_title = $query->title;
}
}
```
A stripped down version of my class:
```
class FB_Events {
private static $_instance = null;
private $wpdb;
public $_token;
public $file;
public $dir;
public $assets_dir;
public $assets_url;
private $message;
public function __construct($file = '', $version = '1.0.0')
{
global $wpdb;
$this->db = $wpdb;
$this->fb_events_table = $this->db->prefix . 'fb_events';
$this->_version = $version;
$this->_token = 'fb_events';
$this->_db_version = '1.0.0';
$this->file = $file;
$this->dir = dirname($this->file);
$this->assets_dir = trailingslashit($this->dir) . 'assets';
$this->assets_url = esc_url(trailingslashit(plugins_url('/assets/', $this->file)));
register_activation_hook($this->file, array($this, 'install'));
add_action('admin_menu', array($this, 'admin_menu'));
add_action('init', array($this, 'rewrite_rules'), 10, 0);
add_filter('query_vars', array($this, 'event_query_var'), 0, 1);
// Add shortcodes for html output
add_shortcode('fb_events_form', array($this, 'add_event_public'));
add_shortcode('fb_events_display', array($this, 'view_events'));
add_shortcode('fb_events_featured', array($this, 'featured_events'));
}
/**
* Register rewrite rules
* @access public
* @since 1.0.0
* @return void
*/
public function rewrite_rules()
{
add_rewrite_rule('^events/add/?', 'index.php?pagename=events/add', 'top');
add_rewrite_rule('^events/([^/]*)/?','index.php?pagename=events&event=$matches[1]', 'top');
}
/**
* Register event query string
* @access public
* @since 1.0.0
* @return void
*/
public function event_query_var($vars)
{
$vars[] = 'event';
return $vars;
}
/**
* View events from public website
* @access public
* @since 1.0.0
* @return void
*/
public function view_events()
{
$event = get_query_var('event');
if(isset($event) && $event != '')
{
if($event != 'add')
{
$event = $this->db->get_row(
$this->db->prepare("
SELECT e.*, u.display_name AS username
FROM {$this->fb_events_table} AS e
LEFT JOIN {$this->db->prefix}users AS u
ON e.user_id = u.id
WHERE e.slug = %s
", $event)
);
if($event > 0)
{
/**
* *********************************
* NEED TO SET <title> to $event->name
* *********************************
*/
ob_start();
if(isset($event->active) && $event->active == 0)
{
//error
}
else
{
//show the event
}
}
else
{
// event does not exist error
}
}
}
}
/**
* Main FB_Events Instance
* @since 1.0.0
* @static
* @return Main FB_Events instance
*/
public static function instance($file = '', $version = '1.0.0') {
if(is_null(self::$_instance))
{
self::$_instance = new self($file, $version);
}
return self::$_instance;
}
}
```
|
As of WP 4.4, wp\_title is deprecated. If you simply need to override your title tag, pre\_get\_document\_title is the filter you want to use.
```
add_filter( 'pre_get_document_title', 'generate_custom_title', 10 );
```
and the function would look something like this
```
function generate_custom_title($title) {
/* your code to generate the new title and assign the $title var to it... */
return $title;
}
```
If you're a stickler you'll know that pre\_get\_document\_title doesn't normally take any args; but if you use the Yoast SEO plugin, you'll find out that this function doesn't do anything! So I *also* hook the 'wpseo\_title' filter onto this same function.
```
add_filter( 'wpseo_title', 'generate_custom_title'), 15 );
```
just in case Yoast is turned on. Code reuse.
|
194,289 |
<p>How to view orders for a specific product in WooCommerce using sku or product name?
What I have so far is that, but it does not work..
Does anyone know how to do?</p>
<pre><code><?php
$args = array(
'post_type' =>'shop_order',
'post_status' => 'publish',
'posts_per_page' => 50,
'order' => 'DESC',
'item_meta' => array (
'_sku' => 'ABCD',
),
'tax_query' => array(
array( 'taxonomy' => 'shop_order_status',
'field' => 'slug',
'terms' => array ('Pending' , 'Failed' , 'Processing' , 'Completed', 'On-Hold' , 'Cancelled' , 'Refunded')
)
)
);
?>
<table id="tblExport" class="demotable1" style="border:1px solid black; ">
<thead>
<tr>
<th ><?php _e('ID:', ' '); ?></th>
<th ><?php _e('sku:', ' '); ?></th>
<th ><?php _e('Categories:', ' '); ?></th>
<th ><?php _e('Product:', ' '); ?></th>
<th ><?php _e('Date:', ' '); ?></th>
<th ><?php _e('Value:', ' '); ?></th>
<th ><?php _e('Name:', ' '); ?></th>
<th ><?php _e('E-mail:', ' '); ?></th>
<th ><?php _e('status:', ' '); ?></th>
</tr>
</thead>
<tbody id="export-pla" >
<?php
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$order_id = $loop->post->ID;
$order = new WC_Order($order_id);
?>
<tr>
<td>
<?php
//ID - order
if ($order->id) : ?><?php echo $order->id; ?><?php endif;?>
</td>
<td>
<?php
//SKU
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] ); echo '' . $_product->sku . ''; } }
?>
</td>
<td>
<?php
// Categories
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] );
echo $_product->get_categories( ', ', '' . _n( '', '', $size, 'woocommerce' ) . ' ', ' ' ); } }
?>
</td>
<td>
<?php
// product name
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] ); echo '' . $item['name'] . ''; } }
?>
</td>
<td>
<?php echo the_time('d/m/Y'); ?>
</td>
<td>
<?php if ($order->order_total): $preco_format=($order->order_total);?>
<?php echo $trata_preco=number_format($preco_format, 2, ",", "."); ?><?php endif; ?>
</td>
<td>
<?php if ($order->billing_first_name) : ?><?php echo $order->billing_first_name; ?><?php endif; ?>
<?php if ($order->billing_last_name) : ?><?php echo $order->billing_last_name; ?><?php endif; ?>
</td>
<td>
<?php if ($order->billing_email) : ?><?php echo $order->billing_email; ?><?php endif; ?>
</td>
<td>
<?php if ($order->status) : ?><?php echo $order->status; ?><?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</tbody>
</table>
</code></pre>
|
[
{
"answer_id": 194657,
"author": "Ericc Antunes",
"author_id": 76267,
"author_profile": "https://wordpress.stackexchange.com/users/76267",
"pm_score": -1,
"selected": false,
"text": "<p>Feito!</p>\n\n<p>Realmente com o WP_Query não dá... pra saber essa informação é necessário utilizar 2 tabelas do WooCommerce.</p>\n\n<p>Então montei a função pra você... ela busca pelo postID do produto e retorna o objeto dos pedidos pra você fazer o loop normal.</p>\n\n<p>É só coloca-la no seu function.php e usa-la em qualquer lugar que quiser! Aqui funcionou bem! Se algo der errado ai, me fala que a gente vê!</p>\n\n<pre><code>function retorna_idpedidos_por_produtoid($produtoId) {\nglobal $wpdb;\n$tabelaOrderItemMeta = $wpdb->prefix . 'woocommerce_order_itemmeta';\n$tabelaOrderItems = $wpdb->prefix . 'woocommerce_order_items';\n\n$resultadoSelect = $wpdb->get_results(\n $wpdb->prepare(\n \"SELECT b.order_id\n FROM {$tabelaOrderItemMeta} a, {$tabelaOrderItems} b\n WHERE a.meta_key = '_product_id'\n AND a.meta_value = %s\n AND a.order_item_id = b.order_item_id\n ORDER BY b.order_id DESC\",\n $produtoId\n )\n);\n\nif($resultadoSelect)\n{\n $resultado = array();\n\n foreach($resultadoSelect as $item)\n array_push($resultado, $item->order_id);\n\n if($resultado)\n {\n $args = array(\n 'post_type' =>'shop_order',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'post__in' => $resultado,\n 'order' => 'DESC'\n );\n $query = new WP_Query($args);\n\n return $query;\n }\n} }\n</code></pre>\n\n<p>Pronto, agora é só fazer o loop, por exemplo:</p>\n\n<pre><code><?php $pedidos = retorna_idpedidos_por_produtoid(33); ?>\n <?php if($pedidos && $pedidos->have_posts()): ?>\n <?php while ($pedidos->have_posts()): $pedidos->the_post(); ?>\n <pre>\n <?php the_ID(); ?>\n </pre>\n <?php endwhile ?>\n <?php endif; ?>\n</code></pre>\n\n<p>Teste aí, espero que dê certo! Abs!</p>\n"
},
{
"answer_id": 195248,
"author": "Thiago",
"author_id": 76088,
"author_profile": "https://wordpress.stackexchange.com/users/76088",
"pm_score": -1,
"selected": true,
"text": "<p>Eric based on your code I wrote to meet my needs, for those who want to follow:</p>\n\n<p>Eric com base em seu código eu escrevi o para atender as minhas necessidades, para quem quiser segue abaixo:</p>\n\n<pre><code><?php\nglobal $wpdb; \n$produto_id = 22777; // ID do produto\n$consulta = \"SELECT order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta woim \n LEFT JOIN {$wpdb->prefix}woocommerce_order_items oi \n ON woim.order_item_id = oi.order_item_id \n WHERE meta_key = '_product_id' AND meta_value = %d\n GROUP BY order_id;\";\n$order_ids = $wpdb->get_col( $wpdb->prepare( $consulta, $produto_id ) );\nif( $order_ids ) {\n $args = array(\n 'post_type' =>'shop_order',\n 'post__in' => $order_ids,\n 'post_status' => 'publish',\n 'posts_per_page' => 20,\n 'order' => 'DESC', \n 'tax_query' => array( \n array( 'taxonomy' => 'shop_order_status',\n 'field' => 'slug',\n 'terms' => array ('Pending' , 'Failed' , 'Processing' , 'Completed', 'On-Hold' , 'Cancelled' , 'Refunded')\n ) \n ) \n );\n $orders = new WP_Query( $args );\n }\n?> \n<table>\n <thead>\n <tr>\n <th ><?php _e('ID do Pedido:', ''); ?></th>\n <th ><?php _e('sku:', ''); ?></th>\n <th ><?php _e('Categoria:', ''); ?></th>\n <th ><?php _e('Produto:', ''); ?></th>\n <th ><?php _e('Data Consolidada da compra:', ''); ?></th>\n <th ><?php _e('Valor:', ''); ?></th>\n <th ><?php _e('Nome:', ''); ?></th>\n <th ><?php _e('Tel:', ''); ?></th>\n <th ><?php _e('End:', ''); ?></th>\n <th ><?php _e('Cidade:', ''); ?></th>\n <th ><?php _e('Estado:', ''); ?></th>\n <th ><?php _e('E-mail:', ''); ?></th>\n <th ><?php _e('status:', ''); ?></th>\n </tr>\n </thead>\n <tbody> \n <?php\n while ( $orders->have_posts() ) : $orders->the_post(); \n $order_id = $orders->post->ID; \n $order = new WC_Order($order_id); \n ?> \n <tr>\n <td>\n <?php\n // Exibe o ID do pedido \n if ($order->id) : ?>\n <a href=\"<?php echo esc_url( home_url('/' ) ); ?>wp-admin/post.php?post=<?php echo $order->id; ?>&action=edit\" target=\"_blank\"><?php echo $order->id; ?></a><?php endif;?>\n </td>\n <td>\n <?php\n // Exibe o SKU\n if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item) \n { $_product = get_product( $item['product_id'] ); echo '' . $_product->sku . ''; } }\n ?> \n </td>\n <td>\n <?php\n // Exibe a Categoria do produto\n if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)\n { $_product = get_product( $item['product_id'] ); \n echo $_product->get_categories( ', ', '' . _n( '', '', $size, 'woocommerce' ) . ' ', ' ' ); } }\n ?>\n </td>\n\n <td>\n <?php\n // Exibe o nome do produto\n if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item) \n { $_product = get_product( $item['product_id'] ); echo '' . $item['name'] . ''; } }\n ?>\n </td> \n <td>\n <?php \n // Exibe a data da copmpra\n echo the_time('d/m/Y'); ?>\n </td>\n <td>\n <?php \n // Exibe o valor da compra + a formatação do preço\n if ($order->order_total): $preco_format=($order->order_total);?>\n <?php echo $trata_preco=number_format($preco_format, 2, \",\", \".\"); ?><?php endif; ?>\n </td>\n <td>\n <?php \n // Exibe o nome e sobrenome do cliente\n if ($order->billing_first_name) : ?><?php echo $order->billing_first_name; ?><?php endif; ?>\n <?php if ($order->billing_last_name) : ?><?php echo $order->billing_last_name; ?><?php endif; ?>\n </td>\n <td>\n <?php \n // Exibe o telefone do cliente\n if ($order->billing_phone) : ?><?php echo $order->billing_phone; ?><?php endif; ?>\n </td>\n <td>\n<?php // Exibe o endereço do cliente\n if ($order->billing_address_1): ?><?php echo $order->billing_address_1; ?>, <?php endif; ?> <?php if ($order->billing_number): ?> <?php echo $order->billing_number; ?><?php endif; ?> <?php if ($order->billing_address_2): ?><?php echo $order->billing_address_2; ?> <?php endif; ?><?php if ($order->billing_neighborhood): ?>Bairro: <?php echo $order->billing_neighborhood; ?><?php endif; ?> <?php if ($order->billing_postcode): ?>Cep: <?php echo $order->billing_postcode; ?><?php endif; ?>\n </td> \n <td>\n <?php \n // Exibe a cidade do cliente\n if ($order->billing_city): ?><?php echo $order->billing_city; ?><?php endif; ?>\n </td>\n <td>\n <?php \n // Exibe o estado do cliente\n if ($order->billing_state): ?><?php echo $order->billing_state; ?><?php endif; ?>\n </td>\n <td>\n <?php \n // Exibe o e-mail do cliente\n if ($order->billing_email) : ?><?php echo $order->billing_email; ?><?php endif; ?>\n </td>\n <td>\n <?php \n // Exibe o status do pedidodo cliente\n if ($order->status) : ?><?php echo $order->status; ?><?php endif; ?>\n </td>\n </tr> \n\n <?php endwhile; ?>\n <?php wp_reset_query(); ?> \n </tbody>\n </table>\n</code></pre>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194289",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76088/"
] |
How to view orders for a specific product in WooCommerce using sku or product name?
What I have so far is that, but it does not work..
Does anyone know how to do?
```
<?php
$args = array(
'post_type' =>'shop_order',
'post_status' => 'publish',
'posts_per_page' => 50,
'order' => 'DESC',
'item_meta' => array (
'_sku' => 'ABCD',
),
'tax_query' => array(
array( 'taxonomy' => 'shop_order_status',
'field' => 'slug',
'terms' => array ('Pending' , 'Failed' , 'Processing' , 'Completed', 'On-Hold' , 'Cancelled' , 'Refunded')
)
)
);
?>
<table id="tblExport" class="demotable1" style="border:1px solid black; ">
<thead>
<tr>
<th ><?php _e('ID:', ' '); ?></th>
<th ><?php _e('sku:', ' '); ?></th>
<th ><?php _e('Categories:', ' '); ?></th>
<th ><?php _e('Product:', ' '); ?></th>
<th ><?php _e('Date:', ' '); ?></th>
<th ><?php _e('Value:', ' '); ?></th>
<th ><?php _e('Name:', ' '); ?></th>
<th ><?php _e('E-mail:', ' '); ?></th>
<th ><?php _e('status:', ' '); ?></th>
</tr>
</thead>
<tbody id="export-pla" >
<?php
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$order_id = $loop->post->ID;
$order = new WC_Order($order_id);
?>
<tr>
<td>
<?php
//ID - order
if ($order->id) : ?><?php echo $order->id; ?><?php endif;?>
</td>
<td>
<?php
//SKU
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] ); echo '' . $_product->sku . ''; } }
?>
</td>
<td>
<?php
// Categories
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] );
echo $_product->get_categories( ', ', '' . _n( '', '', $size, 'woocommerce' ) . ' ', ' ' ); } }
?>
</td>
<td>
<?php
// product name
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] ); echo '' . $item['name'] . ''; } }
?>
</td>
<td>
<?php echo the_time('d/m/Y'); ?>
</td>
<td>
<?php if ($order->order_total): $preco_format=($order->order_total);?>
<?php echo $trata_preco=number_format($preco_format, 2, ",", "."); ?><?php endif; ?>
</td>
<td>
<?php if ($order->billing_first_name) : ?><?php echo $order->billing_first_name; ?><?php endif; ?>
<?php if ($order->billing_last_name) : ?><?php echo $order->billing_last_name; ?><?php endif; ?>
</td>
<td>
<?php if ($order->billing_email) : ?><?php echo $order->billing_email; ?><?php endif; ?>
</td>
<td>
<?php if ($order->status) : ?><?php echo $order->status; ?><?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</tbody>
</table>
```
|
Eric based on your code I wrote to meet my needs, for those who want to follow:
Eric com base em seu código eu escrevi o para atender as minhas necessidades, para quem quiser segue abaixo:
```
<?php
global $wpdb;
$produto_id = 22777; // ID do produto
$consulta = "SELECT order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta woim
LEFT JOIN {$wpdb->prefix}woocommerce_order_items oi
ON woim.order_item_id = oi.order_item_id
WHERE meta_key = '_product_id' AND meta_value = %d
GROUP BY order_id;";
$order_ids = $wpdb->get_col( $wpdb->prepare( $consulta, $produto_id ) );
if( $order_ids ) {
$args = array(
'post_type' =>'shop_order',
'post__in' => $order_ids,
'post_status' => 'publish',
'posts_per_page' => 20,
'order' => 'DESC',
'tax_query' => array(
array( 'taxonomy' => 'shop_order_status',
'field' => 'slug',
'terms' => array ('Pending' , 'Failed' , 'Processing' , 'Completed', 'On-Hold' , 'Cancelled' , 'Refunded')
)
)
);
$orders = new WP_Query( $args );
}
?>
<table>
<thead>
<tr>
<th ><?php _e('ID do Pedido:', ''); ?></th>
<th ><?php _e('sku:', ''); ?></th>
<th ><?php _e('Categoria:', ''); ?></th>
<th ><?php _e('Produto:', ''); ?></th>
<th ><?php _e('Data Consolidada da compra:', ''); ?></th>
<th ><?php _e('Valor:', ''); ?></th>
<th ><?php _e('Nome:', ''); ?></th>
<th ><?php _e('Tel:', ''); ?></th>
<th ><?php _e('End:', ''); ?></th>
<th ><?php _e('Cidade:', ''); ?></th>
<th ><?php _e('Estado:', ''); ?></th>
<th ><?php _e('E-mail:', ''); ?></th>
<th ><?php _e('status:', ''); ?></th>
</tr>
</thead>
<tbody>
<?php
while ( $orders->have_posts() ) : $orders->the_post();
$order_id = $orders->post->ID;
$order = new WC_Order($order_id);
?>
<tr>
<td>
<?php
// Exibe o ID do pedido
if ($order->id) : ?>
<a href="<?php echo esc_url( home_url('/' ) ); ?>wp-admin/post.php?post=<?php echo $order->id; ?>&action=edit" target="_blank"><?php echo $order->id; ?></a><?php endif;?>
</td>
<td>
<?php
// Exibe o SKU
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] ); echo '' . $_product->sku . ''; } }
?>
</td>
<td>
<?php
// Exibe a Categoria do produto
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] );
echo $_product->get_categories( ', ', '' . _n( '', '', $size, 'woocommerce' ) . ' ', ' ' ); } }
?>
</td>
<td>
<?php
// Exibe o nome do produto
if (sizeof($order->get_items())>0) { foreach($order->get_items() as $item)
{ $_product = get_product( $item['product_id'] ); echo '' . $item['name'] . ''; } }
?>
</td>
<td>
<?php
// Exibe a data da copmpra
echo the_time('d/m/Y'); ?>
</td>
<td>
<?php
// Exibe o valor da compra + a formatação do preço
if ($order->order_total): $preco_format=($order->order_total);?>
<?php echo $trata_preco=number_format($preco_format, 2, ",", "."); ?><?php endif; ?>
</td>
<td>
<?php
// Exibe o nome e sobrenome do cliente
if ($order->billing_first_name) : ?><?php echo $order->billing_first_name; ?><?php endif; ?>
<?php if ($order->billing_last_name) : ?><?php echo $order->billing_last_name; ?><?php endif; ?>
</td>
<td>
<?php
// Exibe o telefone do cliente
if ($order->billing_phone) : ?><?php echo $order->billing_phone; ?><?php endif; ?>
</td>
<td>
<?php // Exibe o endereço do cliente
if ($order->billing_address_1): ?><?php echo $order->billing_address_1; ?>, <?php endif; ?> <?php if ($order->billing_number): ?> <?php echo $order->billing_number; ?><?php endif; ?> <?php if ($order->billing_address_2): ?><?php echo $order->billing_address_2; ?> <?php endif; ?><?php if ($order->billing_neighborhood): ?>Bairro: <?php echo $order->billing_neighborhood; ?><?php endif; ?> <?php if ($order->billing_postcode): ?>Cep: <?php echo $order->billing_postcode; ?><?php endif; ?>
</td>
<td>
<?php
// Exibe a cidade do cliente
if ($order->billing_city): ?><?php echo $order->billing_city; ?><?php endif; ?>
</td>
<td>
<?php
// Exibe o estado do cliente
if ($order->billing_state): ?><?php echo $order->billing_state; ?><?php endif; ?>
</td>
<td>
<?php
// Exibe o e-mail do cliente
if ($order->billing_email) : ?><?php echo $order->billing_email; ?><?php endif; ?>
</td>
<td>
<?php
// Exibe o status do pedidodo cliente
if ($order->status) : ?><?php echo $order->status; ?><?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</tbody>
</table>
```
|
194,291 |
<p>I've setup a brand new CentOS 7 VPS; everything configured by me. LAMP installation and the Apache virtual host configurations are all done. I've checked them before installing Wordpress and the HTML sites were being showed as well as the PHP info and everything else.</p>
<p>After that I went on to setup Wordpress as usual. Then I tried to log-in(the log-in page got loaded successfully) but the log-in page directed me to an error message of <code>403 Forbidden: You don't have permission to access /wp-admin/ on this server.</code></p>
<p>What seems to be the issue? I've a separate user than <code>root</code> managing the VPS whom also has root privileges and it also has ownership on the Wordpress files. Also the files and folder all have 755 as their permissions. Is this a <code>.htaccess</code> issue?</p>
<p>A detailed explanation would be much appreciated. Thanks.</p>
<p>P.S. Also my firewall is not yet installed</p>
|
[
{
"answer_id": 194302,
"author": "Nick",
"author_id": 65003,
"author_profile": "https://wordpress.stackexchange.com/users/65003",
"pm_score": 3,
"selected": true,
"text": "<p>Add this in your .htaccess file at website root folder.\nIf you deleted it then create it again and paste this.</p>\n\n<pre><code>DirectoryIndex index.html index.php\n\n# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Looks like you have issue with <code>DirectoryIndex</code>.\nIn your <code>httpd.conf</code> search for <code>DirectoryIndex</code> and make sure you add index.php in it.\nOr in your virtual host configuration.</p>\n\n<p>Like this.</p>\n\n<pre><code>DirectoryIndex index.html index.htm index.php\n</code></pre>\n"
},
{
"answer_id": 330301,
"author": "Paul",
"author_id": 162257,
"author_profile": "https://wordpress.stackexchange.com/users/162257",
"pm_score": 0,
"selected": false,
"text": "<p>I had two directory callouts to the same directory. one was placed in the regular httpd.conf file and the other was in my virtual host conf. As soon as I deleted the one in the regular conf, my virtual host wp-admin began working.</p>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76091/"
] |
I've setup a brand new CentOS 7 VPS; everything configured by me. LAMP installation and the Apache virtual host configurations are all done. I've checked them before installing Wordpress and the HTML sites were being showed as well as the PHP info and everything else.
After that I went on to setup Wordpress as usual. Then I tried to log-in(the log-in page got loaded successfully) but the log-in page directed me to an error message of `403 Forbidden: You don't have permission to access /wp-admin/ on this server.`
What seems to be the issue? I've a separate user than `root` managing the VPS whom also has root privileges and it also has ownership on the Wordpress files. Also the files and folder all have 755 as their permissions. Is this a `.htaccess` issue?
A detailed explanation would be much appreciated. Thanks.
P.S. Also my firewall is not yet installed
|
Add this in your .htaccess file at website root folder.
If you deleted it then create it again and paste this.
```
DirectoryIndex index.html index.php
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
EDIT
----
Looks like you have issue with `DirectoryIndex`.
In your `httpd.conf` search for `DirectoryIndex` and make sure you add index.php in it.
Or in your virtual host configuration.
Like this.
```
DirectoryIndex index.html index.htm index.php
```
|
194,309 |
<p>I know it sounds like a Basic Question and I did google first. Google lead me to edit /wp-admin/edit-form-advanced.php to put target='_blank' there. I did that, but this doesn't seem to affect the 'view page' button on the top of the edit page site.
I want it to open in a new tab every time.</p>
<p>In what file/where can I find that button?
Can you give advice on how to systematically search such a location for the future?</p>
<p>What is the proper way of doing that and why.</p>
<p>Thanks for letting me know</p>
|
[
{
"answer_id": 194302,
"author": "Nick",
"author_id": 65003,
"author_profile": "https://wordpress.stackexchange.com/users/65003",
"pm_score": 3,
"selected": true,
"text": "<p>Add this in your .htaccess file at website root folder.\nIf you deleted it then create it again and paste this.</p>\n\n<pre><code>DirectoryIndex index.html index.php\n\n# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Looks like you have issue with <code>DirectoryIndex</code>.\nIn your <code>httpd.conf</code> search for <code>DirectoryIndex</code> and make sure you add index.php in it.\nOr in your virtual host configuration.</p>\n\n<p>Like this.</p>\n\n<pre><code>DirectoryIndex index.html index.htm index.php\n</code></pre>\n"
},
{
"answer_id": 330301,
"author": "Paul",
"author_id": 162257,
"author_profile": "https://wordpress.stackexchange.com/users/162257",
"pm_score": 0,
"selected": false,
"text": "<p>I had two directory callouts to the same directory. one was placed in the regular httpd.conf file and the other was in my virtual host conf. As soon as I deleted the one in the regular conf, my virtual host wp-admin began working.</p>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76102/"
] |
I know it sounds like a Basic Question and I did google first. Google lead me to edit /wp-admin/edit-form-advanced.php to put target='\_blank' there. I did that, but this doesn't seem to affect the 'view page' button on the top of the edit page site.
I want it to open in a new tab every time.
In what file/where can I find that button?
Can you give advice on how to systematically search such a location for the future?
What is the proper way of doing that and why.
Thanks for letting me know
|
Add this in your .htaccess file at website root folder.
If you deleted it then create it again and paste this.
```
DirectoryIndex index.html index.php
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
EDIT
----
Looks like you have issue with `DirectoryIndex`.
In your `httpd.conf` search for `DirectoryIndex` and make sure you add index.php in it.
Or in your virtual host configuration.
Like this.
```
DirectoryIndex index.html index.htm index.php
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.